在Kotlin中编号为MutableList <Int>的奇数大小返回带有迭代器的IndexOutOfBoundsException
使用下面的代码运行测试会返回一个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,并且当您尝试访问索引75
处的元素时,最终会出现IndexOutOfBoundsException
,这是不存在的。
如果你想迭代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) }
您正在迭代所有数字1..75
但索引从0开始。从项目中减1
将为您提供正确的值索引。
for(n in mList.iterator()) { println(mList[n - 1]) }
但最终甚至不是你打算做的。 您可能需要直接打印项目或遍历索引0..mList.size-1
本身。