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

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.

Leave a Comment