Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 650
adamfinstorp Avatar asked Sep 13 '11 23:09

adamfinstorp


People also ask

Can we add element in list while iterating Java?

You can't modify a Collection while iterating over it using an Iterator , except for Iterator. remove() . 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.

Can we modify list while iterating in Java?

The Best Answer is It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Can we add elements while iterating ArrayList?

ListIterator supports to add and remove elements in the list while we are iterating over it. listIterator. add(Element e) – The element is inserted immediately before the element that would be returned by next() or after the element that would be returned previous() method.

Can we add elements using iterator?

The add() method of ListIterator interface is used to insert the given element into the specified list. The element is inserted automatically before the next element may return by next() method.


1 Answers

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.

like image 110
Bohemian Avatar answered Sep 20 '22 22:09

Bohemian