previous in List Iterator of Java

孤者浪人 提交于 2021-02-05 12:21:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!