java - 在java中使用ListIterator作为LinkedList时遇到问题

标签 java iterator linked-list

是否可以使用 ListIterator 遍历 Java 中的 LL,定期将对象添加到列表中,并按照添加顺序处理列表中的这些项目?

假设我从一个包含单个对象的 LL 开始。我处理这个对象,并决定添加两个额外的对象,我想进一步处理它们(如 FIFO)。直觉上,我从

开始这个过程
while (itr.hasNext()) {
itr.next();
...
itr.add();
}

但是,这似乎很快就会崩溃 - add 实际上是在我当前所在的索引之前添加项目,而不是在( ListIterator javadoc )之后。这意味着当我再次启动 while 循环时,它实际上无法识别已将内容添加到 LL 中,因为它实际上需要向后运行(.hasPrevious() 而不是 。 hasNext()) 来查找它。但我无法使用 .hasPrevious() 启动 LL(我不认为),因为 LL 中的第一项是 .next() 项。

如何干净利落地做到这一点?还是我只是个傻子?

最佳答案

您没有在上面的评论中引用完整的定义:

Inserts the specified element into the list (optional operation). The element is inserted immediately before the next element that would be returned by next, if any, and after the next element that would be returned by previous, if any. (If the list contains no elements, the new element becomes the sole element on the list.) 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. (This call increases by one the value that would be returned by a call to nextIndex or previousIndex.)

新项目已插入,因此您必须调用 previous() 才能获取它。

如果你必须在当前迭代点插入项,那么你将必须自己进行管理并调用 previous(),这将涉及到稍微重构循环。

如果您可以将新项目添加到列表末尾并稍后处理它们,请改用队列实现。

关于java - 在java中使用ListIterator作为LinkedList时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3167523/

相关文章:

java - 如何仅选择性地从 .txt 文件中读取数字和/或单词?

linked-list - MIPS链表

Java - 当我们在自己的类中创建类型类的数据类型时会发生什么?

Java - 设置装饰 JFrame 的大小

c++ - 从成对 vector 中获取值时出错

c++ - 如何在模板中定义迭代器?

c++ - std::set 具有相同键和不同比较器的迭代器

java - 在类中实现类

java - 号码跑者计划

java - Spring 4.0.1 + quartz 1.5.2