I have the following code showing how ListIterator works but it appears the items returned by the iterator are not what I expected.
import java.util.*;
public class IteratorExample {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("A");
al.add("B");
al.add("C");
ListIterator litr = al.listIterator();
System.out.print(litr.next()); // expect A
System.out.print(litr.next()); // expect B
System.out.print(litr.next()); // expect C
System.out.print(litr.previous()); // expect B
System.out.print(litr.previous()); // expect A
System.out.print(litr.next()); // expect B
System.out.print(litr.previous()); // expect A
}}
I expected to see "ABCBABA", but the sample program gives me "ABCCBBB". Can anyone explain how iterator works? What should I do if I want to end up with the result "ABCBABA" by just using the iterator?
Here's another simple way to understand this behavior.
next() --> Return the next element and advance the cursor by one element so that now the cursor points to next to next element.
previous() --> Return the previous element and move the cursor backward by one element so that the cursor points to the previous element.
Just after your list is created, the iterator position is something like following:
So the output is rightly "ABCCBBB"