在迭代列表时将元素添加到列表中.(爪哇)

时间:2023-02-25
本文介绍了在迭代列表时将元素添加到列表中.(爪哇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Java:在迭代期间向集合添加元素

我的问题是我想在迭代时用新元素扩展一个列表,并且我希望迭代器继续使用我刚刚添加的元素.

My problem is that I want to expand a list with new elements while iterating over it and I want the iterator to continue with the elements that I just added.

据我了解,ListIterator.add() 在列表中的当前元素之前添加一个元素,而不是在它之后.是否有可能以其他方式实现这一目标?

From my understanding the ListIterator.add() adds an element before the current element in the list, not after it. Is it possible to achieve this in some other way?

推荐答案

您不能在使用 Iterator 迭代时修改 Collection,除了 Iterator.remove().

You can't modify a Collection while iterating over it using an Iterator, except for Iterator.remove().

但是,如果您使用 listIterator() 方法,它返回一个 ListIterator,并迭代你有更多的选项可以修改.来自 add() 的 javadoc:

However, if you use the listIterator() method, which returns a ListIterator, and iterate over that you have more options to modify. From the javadoc for add():

新元素被插入到隐式游标之前:... 对 previous() 的后续调用将返回新元素

The new element is inserted before the implicit cursor: ... a subsequent call to previous() would return the new element

鉴于此,这段代码应该可以将新元素设置为迭代中的下一个:

Given that, this code should work to set the new element as the next in the iteration:

ListIterator<T> i;
i.add(e);
i.previous(); // returns e
i.previous(); // returns element before e, and e will be next

这将起作用,除非列表开始迭代为空,在这种情况下将没有前一个元素.如果这是一个问题,您将不得不维护某种标志来指示这种极端情况.

This will work except when the list starts iteration empty, in which case there will be no previous element. If that's a problem, you'll have to maintain a flag of some sort to indicate this edge case.

这篇关于在迭代列表时将元素添加到列表中.(爪哇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!