問題描述
可能重復(fù):
Java:在迭代期間向集合添加元素
我的問題是我想在迭代時用新元素擴(kuò)展一個列表,并且我希望迭代器繼續(xù)使用我剛剛添加的元素.
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.
據(jù)我了解,ListIterator.add()
在列表中的當(dāng)前元素之前添加一個元素,而不是在它之后.是否有可能以其他方式實現(xiàn)這一目標(biāo)?
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()
:
新元素被插入到隱式游標(biāo)之前:... 對 previous()
的后續(xù)調(diào)用將返回新元素
The new element is inserted before the implicit cursor: ... a subsequent call to
previous()
would return the new element
鑒于此,這段代碼應(yīng)該可以將新元素設(shè)置為迭代中的下一個:
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
這將起作用,除非列表開始迭代為空,在這種情況下將沒有前一個元素.如果這是一個問題,您將不得不維護(hù)某種標(biāo)志來指示這種極端情況.
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.
這篇關(guān)于在迭代列表時將元素添加到列表中.(爪哇)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!