英文:
Is iterator's rule of Iterator and Listiterator different from each other?(Java)
问题
以下是您要翻译的内容:
我正在练习Java代码 - iterator
和 listIterator
,并且对以下代码的结果感到困惑。
代码:
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();
}
}
结果:
A B C D
D C C-add B A-add A
A A-add B C-add C D
我想知道为什么在第一个while循环中没有打印出A-add
(在第一个while循环中),但在第二个while循环中打印出了C-add
(在第二个while循环中)。
它们都只是新添加到现有列表中,而且while循环结构是相似的(我认为是这样的)。
有人能解释一下这个吗?
英文:
I'm practicing Java code - iterator
and listIterator
<br>
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:
> A B C D <br>
> D C C-add B A-add A <br>
> A A-add B C-add C D <br>
I wonder why A-add
is not printed (in the first while loop), but C-add
is printed (in the second while loop).
Both of them are just newly added to the existing list, and the while loop structure is alike (I think?).
Can anyone explain this?
答案1
得分: 5
这在ListIterator.add
的文档中有解释:
> [...] 新元素被插入在隐式游标之前:随后对next的调用不受影响,并且对previous的调用将返回新元素。
因此在您的示例中(^
表示游标位置)
- 第一次迭代(正向):
A B 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 ^ →
英文:
This is explained by the documentation of 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.
So in your example (^
indicating the cursor)
- First iteration (forward):
A B C D ^ → // litr.add("A-add"); A A-add B C D ^ →
- Second iteration (backward)
A A-add B C D ← ^ // litr.add("C-add"); A A-add B C-add C D ← ^
- Third iteration (forward)
A A-add B C-add C D ^ →
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论