n0manarmy
n0manarmy

Reputation: 109

Odd size numbered MutableList<Int> in Kotlin returns IndexOutOfBoundsException with iterator

Running a test with the code below returns a java.lang.IndexOutOfBoundsException: Index 75, Size: 75.

This does not happen on even numbered lists, only odd numbered lists. Am I doing this wrong? Iterating in Java does not seem to do this.

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

Upvotes: 1

Views: 605

Answers (2)

zsmb13
zsmb13

Reputation: 89608

mList contains these numbers, with these indexes:

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

Therefore, if you index mList with the contents of mList itself, that means accessing indexes 1 through 75, which will give you the numbers 2 through 75 for the first 74 accesses, and finally an IndexOutOfBoundsException when you try to access the element at index 75, which doesn't exist.

If you want to iterate over mList and print its elements, you have several ways to do that:

// 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) }

Upvotes: 4

tynn
tynn

Reputation: 39853

You are iterating over all numbers 1..75 but indexing starts at 0. Subtracting 1 from the item would give you the correct index to the value.

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

But eventually it's not even what you intended to do at all. You might want to print the item directly or iterate over the indices 0..mList.size-1 itself.

Upvotes: 1

Related Questions