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?
You can’t modify a Collection while iterating over it using an
Iterator, except forIterator.remove().However, if you use the
listIterator()method, which returns aListIterator, and iterate over that you have more options to modify. From the javadoc foradd():Given that, this code should work to set the new element as the next in the iteration:
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.