Kotlin中编号为MutableList <int>的奇数大小使用迭代器返回IndexOutOfBoundsException

时间:2017-06-19 13:10:47

标签: exception iterator kotlin

使用以下代码运行测试会返回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])
}

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:1)

您正在迭代所有数字1..75,但索引从0开始。从项目中减去1将为您提供正确的值索引。

for(n in mList.iterator()) {
    println(mList[n - 1])
}

但最终它根本不是你打算做的。您可能希望直接打印项目或迭代索引0..mList.size-1本身。