Let's say I run this code, it shows me this : 1 10 2 10 3 10
public class Test1{
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add((1));
list.add((2));
list.add((3));
ListIterator<Integer> it = list.listIterator();
while(it.hasNext()){
it.next();
it.add((10));
}
for(Integer i : list){
System.out.println(i);
}
}
What I don't get is why the last hasNext()
takes place even thought we should be at the end of the list (in my understanding). On the element 3.
First, iterator is on 1. hasNext()
return true
because list has 2 after.
So i go into the loop, it.next()
returns me 1 and set the cursor on 2. When I add 10 it takes place in the cursor place so between 1 and 2.
then, it.next()
returns me 2 and set the cursor to 3. Then I add 10 between 2 and 3.
But at this point, I don't have the next of 3, so why do hasNext()
return true, to add 12 at the last place of the list?
Iterators in Java are created to point to the place before the start of the list, so the first call to
next()
returns the first element, if the list has one. Thus, you will go over all the items of the list, and add10
after each one.