简体   繁体   中英

previous in List Iterator of Java

I use the list iterator of Java, and I don't understand how does the previous method work. I get the next element of the Linked list "B" and then I try to get the previous element "A" but I get "B".

LinkedList<Character> abc = new LinkedList<Character>();
abc.add('A');
abc.add('B');
ListIterator<Character> iterator = abc.listIterator();
System.out.println(iterator.next());
System.out.println(iterator.next());
System.out.println(iterator.previous());

The output is "A", "B", "B".

Why doesn't it work, and how does it work behind the scenes?

From JavaDocs:

Returns the previous element in the list and moves the cursor position backwards. This method may be called repeatedly to iterate through the list backwards, or intermixed with calls to next to go back and forth. (Note that alternating calls to next and previous will return the same element repeatedly.)

Important part here is: (Note that alternating calls to next and previous will return the same element repeatedly.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM