ListIterator last hasNext () something incomprehensible

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

      

I do not understand why the latter hasNext()

is the case, even if we think that we should be at the end of the list (in my understanding). On element 3.

First, the iterator is at 1. hasNext()

return true

because the list has 2 after. So I go into a loop, it it.next()

returns 1 to me and sets the cursor to 2. When I add 10, it happens at the cursor location, so between 1 and 2. it it.next()

returns 2 to me and sets the cursor to 3. Then I add 10 between 2 and 3 But at the moment I don't have the next of 3, so why does it hasNext()

return true to add 12 to the last place in the list?

+3


source to share


2 answers


Iterators in Java are designed to point to a location before the start of a list , so the first call next()

returns the first element if there is one in the list. This way, you will loop through all the list items and add 10

after each one.



+3


source


The cursor is always between items. When you add an item via a list iterator, the item is added at the cursor position, and the cursor moves after the item you just inserted. This is also explained in the javadoc .

Think about the cursor position in such a way that:



    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

      

+2


source







All Articles