Add elements to a List while iterating over it. (Java) [duplicate]

丶灬走出姿态 提交于 2019-11-26 12:45:20

问题


Possible Duplicate:
Java: adding elements to a collection during iteration

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.

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?


回答1:


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

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():

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.




回答2:


There might be some trick with ListIterator, but the easiest solution is probably an old style index loop. Verify performance isn't an issue (no linked lists - but ArrayList is fine).

List<Object> myList;

for(int i = 0; i < myList.size(); i++)
{
  Object current = myList.get(i); 
  // Anything you insert after i will be discovered during next iterations
}



回答3:


How about

List<Foo> fooList = getFooList();
List<Foo> tempFooList = new ArrayList<Foo>()


for(Foo f : fooList)
{
   ...
   // add items that need to be added to temp
   tempFooList.add(new Foo());
   ...
}

fooList.addAll(tempFooList);


来源:https://stackoverflow.com/questions/7409740/add-elements-to-a-list-while-iterating-over-it-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!