I'm trying to learn the ListIterator interface. I have came up with two version of the code,
List<Integer> list1 = new LinkedList<>(Arrays.asList(11,22,33,44));
ListIterator<Integer> it = list1.listIterator();
while (it.hasNext()){
//version 1
System.out.println("value: " + it.next() + " index: " + it.nextIndex());
//version 2
System.out.println("index: " + it.nextIndex() + " value: " + it.next());
}
Result of version 1:
value: 11 index: 1
value: 22 index: 2
value: 33 index: 3
value: 44 index: 4
Result of version 2:
index: 0 value: 11
index: 1 value: 22
index: 2 value: 33
index: 3 value: 44
I was expecting the result to be the same, but obviously they are not. Could someone please tell me why?
When calling it.next()
first, it.nextIndex()
will return the index of the element after it.next()
s result, since it.next() will return the value at the current index and then subsequently increment the index.
Visual example:
it.next()
first:
v
index 0 1 2 3
value 11 22 33 44
call it.next() -> returns 11, increments index by 1
v
index 0 1 2 3
value 11 22 33 44
call it.nextIndex() -> returns 1
it.nextIndex()
first:
v
index 0 1 2 3
value 11 22 33 44
call it.nextIndex() -> returns 0
v
index 0 1 2 3
value 11 22 33 44
call it.nextIndex() -> returns 11, increments index by 1
v
index 0 1 2 3
value 11 22 33 44