[英]Is iterator's rule of Iterator and Listiterator different from each other?(Java)
I'm practicing Java code - iterator
and listIterator
我正在练习 Java 代码 - iterator
和listIterator
and having a hard time understanding the result of the code below.并且很难理解下面代码的结果。
Code :代码:
import java.util.*;
public class ListIteratorCollection {
public static void main(String[] args) {
List<String> list = Arrays.asList("A","B","C","D");
list = new ArrayList<>(list);
ListIterator<String> litr = list.listIterator();
String str;
while(litr.hasNext()){
str = litr.next();
System.out.print(str + '\t');
if(str.equals("A"))
litr.add("A-add");
}
System.out.println();
while(litr.hasPrevious()){
str = litr.previous();
System.out.print(str + '\t');
if(str.equals("C"))
litr.add("C-add");
}
System.out.println();
for(Iterator<String> itr = list.iterator(); itr.hasNext();)
System.out.print(itr.next() + '\t');
System.out.println();
}
}
Result :结果:
AB C D AB C D
D C C-add B A-add A D C C-加B A-加A
A A-add B C-add C D A A-添加 B C-添加 C D
I wonder why A-add
is not printed (in the first while loop), but C-add
is printed (in the second while loop).我想知道为什么不打印A-add
(在第一个 while 循环中),但打印C-add
(在第二个 while 循环中)。 Both of them are just newly added to the existing list, and the while loop structure is alike (I think?).两者都只是新添加到现有列表中,while 循环结构很相似(我想?)。
Can anyone explain this?谁能解释一下?
This is explained by the documentation of ListIterator.add
: ListIterator.add
的文档解释了这一点:
[...] 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. [...] 在隐式 cursor 之前插入新元素:对 next 的后续调用将不受影响,对 previous 的后续调用将返回新元素。
So in your example ( ^
indicating the cursor)所以在你的例子中( ^
表示光标)
AB C D ^ → // litr.add("A-add"); A A-add B C D ^ →
A A-add B C D ← ^ // litr.add("C-add"); A A-add B C-add C D ← ^
A A-add B C-add C D ^ →
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.