迭代时向元素添加元素。 (JAVA) [英] Add elements to a List while iterating over it. (Java)

查看:148
本文介绍了迭代时向元素添加元素。 (JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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?

推荐答案

使用<迭代它时,无法修改集合code> Iterator ,但 Iterator.remove()除外。

但是,如果您使用 listIterator() 方法,返回 ListIterator ,并迭代你有更多选项可以修改。从的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()将返回新元素

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

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.

这篇关于迭代时向元素添加元素。 (JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆