Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add element in List while iterating in java?

Say I have a List like:

List<String> list = new ArrayList<>(); list.add("a"); list.add("h"); list.add("f"); list.add("s"); 

While iterating through this list I want to add an element at the end of the list. But I don't want to iterate through the newly added elements that is I want to iterate up to the initial size of the list.

for (String s : list)      /* Here I want to add new element if needed while iterating */ 

Can anybody suggest me how can I do this?

like image 243
flyleaf Avatar asked Jun 24 '12 12:06

flyleaf


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 add elements to ArrayList while iterating?

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 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 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 use a foreach statement for that. The foreach is using internally an iterator:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

(From ArrayList javadoc)

In the foreach statement you don't have access to the iterator's add method and in any case that's still not the type of add that you want because it does not append at the end. You'll need to traverse the list manually:

int listSize = list.size(); for(int i = 0; i < listSize; ++i)   list.add("whatever"); 

Note that this is only efficient for Lists that allow random access. You can check for this feature by checking whether the list implements the RandomAccess marker interface. An ArrayList has random access. A linked list does not.

like image 58
yankee Avatar answered Sep 21 '22 18:09

yankee