gpt4 book ai didi

exception - Kotlin中编号为MutableList 的奇数大小返回带有迭代器的IndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-02 13:06:39 27 4
gpt4 key购买 nike

使用下面的代码运行测试将返回java.lang.IndexOutOfBoundsException:索引75,大小:75。

在偶数列表,只有奇数列表上不会发生这种情况。我做错了吗?在Java中进行迭代似乎无法做到这一点。

var mList: MutableList<Int> = mutableListOf()
for(n in 1..75) {
mList.add(n)
}
for(n in mList.iterator()) {
println(mList[n])
}

最佳答案

mList包含以下数字以及这些索引:

[ 1, 2, 3, 4, ... , 73, 74, 75]   list contents
0 1 2 3 ... 72 73 74 indexes

因此,如果您使用 mList本身的内容对 mList进行索引,则意味着通过 1访问索引 75,这将为您进行前74次访问提供2到75的数字,最后是当您尝试在索引 IndexOutOfBoundsException上访问元素时的 75。 ,这不存在。

如果要遍历 mList并打印其元素,则可以通过以下几种方法进行:
// using indexes with `until`
for(i in 0 until mList.size) { println(mList[i]) }

// using `.indices` to get the start and end indexes
for(i in mList.indices) { println(mList[i]) }

// range-for loop
for(i in mList) { println(i) }

// functional approach
mList.forEach { println(it) }

关于exception - Kotlin中编号为MutableList <Int>的奇数大小返回带有迭代器的IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44631514/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com