javalistiterator

ListIterator previous() and next() result


result is

A B C D

D C C2 B2 B A

Why isn't result

A B B2 C D

D C C2 B2 B A in first while ?

I did li.add("B2") if word.equals"B". Is it just difference between next() and previous() ? I want to know answer please.

public static void main(String[] args) {

    List<String> list = Arrays.asList("A", "B", "C", "D");
    list = new ArrayList<>(list);
    ListIterator<String> li = list.listIterator();
    String word;

    while (li.hasNext()) {
        word = li.next();
        System.out.print(word + '\t');
        if (word.equals("B"))
           li.add("B2");
    }

    System.out.println();

    while (li.hasPrevious()) {
        word = li.previous();
        System.out.print(word + '\t');
        if (word.equals("C"))
            li.add("C2");
    }
}

Solution

  • I think that answer for your question is here - https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#add(E).

    The element is inserted immediately before the element that would be returned by next(), if any, and after the element that would be returned by previous(), if any.

    The new element is inserted before the implicit cursor: a subsequent call to next would be unaffected, and a subsequent call to previous would return the new element.

    At first loop when word equals "B" the implicit cursor is between "B" and "C", according to the documentation the new element will be added before it.

    A    B       C     D
           ^   ^ 
          B2  cursor