问题
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?
回答1:
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.)
来源:https://stackoverflow.com/questions/52222143/previous-in-list-iterator-of-java