根据 Java 文档:
A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of length n has n+1 possible cursor positions, as illustrated by the carets (^) below:
我的问题是,例如,假设 while 循环正在运行,按下 2 后,我调用一个方法
public void callNextElement(int choice, LinkedList<String> linkedList) {
ListIterator<String> listIterator = linkedList.listIterator();
if (choice == 2) {
if (listIterator.hasNext()){
listIterator.next();
System.out.println("We have: " + listIterator.next());
}
}
}
现在,这将打印第一个元素并返回到 while 循环以获取输入,现在再次按 2,我将获得列表的第一个元素/条目。如果我这样做了:
System.out.println("We have: " + listIterator.next());
System.out.println("We have: " + listIterator.next());
System.out.println("We have: " + listIterator.next());
System.out.println("We have: " + listIterator.next());
....
这将打印链接列表中的其他元素
所以我的问题是:
为什么我调用的方法中没有打印出第二个元素等?
为什么它仅在连续调用 listiterator.next() 时才有效,就像我通过在上面打印它们所做的那样?
如果 listiterator 实际上存储下一个元素位置,以便即使调用
next()
(不连续)它也会打印下一个元素,会发生什么?不是第一个。
编辑:
我觉得自己很蠢,但是 Java 的垃圾收集在我的方法调用中起作用了吗?如果是,那么每次打印第一个元素就有意义了。我是 Java 新手,完全忘记了这一点......
最佳答案
每个列表迭代器在列表中都有自己独立的位置。每次调用listIterator()
时,您都会得到一个从列表开头开始的新迭代器。
ListIterator<String> listIterator = linkedList.listIterator();
如果您想迭代连续的元素,则需要调用一次 listIterator()
并将迭代器保存在某处,以便可以重复使用。
关于java - 为什么 list-iterator.next();返回到 "no current element"位置,除非迭代多次直到结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52172651/