ListIterator last hasNext() something not understood

198 views Asked by At

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?

2

There are 2 answers

0
Mureinik On

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 add 10 after each one.

0
assylias On

The cursor is always between elements. When you add an element via the list iterator, the item is added at the cursor's position and the cursor is moved to after the item you just inserted. This is also explained in the javadoc.

Think of the cursor position that way, in order:

    1      2       3
  ^
hasNext? yes => call next (returns 1)
    1      2       3
        ^
call add
    1      10      2       3
               ^
hasNext? yes => call next (returns 2)
    1      10      2       3
                       ^
call add
    1      10      2       10         3
                                ^
hasNext? yes => call next (returns 3)
    1      10      2       10         3
                                           ^
call add
    1      10      2       10         3       10
                                                       ^
hasNext? no => exit loop