Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid ConcurrentModificationException while iterating this collection?

I need to iterate over a collection of items & sometimes add to that collection at the same time. However, incase I add while iterating then I just start the iteration from fresh by breaking out of iteration loop & restarting iteration from beginning. However this leads to ConcurrentModificationException. [code below]

    List<Integer> collection = new ArrayList<>();
    for (Integer lobId: collection) {
         ..
         if (someCondition) {
             collection.add(something); 
             break; 
         }
    }

How could I possibly do something like above avoiding ConcurrentModificationException?

Would it be correct to simply use an Array instead of ArrayList to avoid this exception ? Is there any type of specialized collection for this ?

--

Edit:

I dont want to create a new copy for this arraylist because I'm repeating this entire iteration process multiple times unless some requirement is completed. Creating a new copy each time would bring in some extra overhead, which I would like to avoid if somehow possible.

Also if possible I would like to maintain a sorted order & unique values in that collection. Is there anything that is ready to use in any library? Otherwise I could sort it at the end of iteration process & remove duplicates. That will also do fine for me.

like image 948
Rajat Gupta Avatar asked Feb 02 '14 07:02

Rajat Gupta


1 Answers

Use another collection for the additions and combine them at the end.

List<Integer> collection = new ArrayList<>();
collection.add(...)
...
List<Integer> tempCollection = new ArrayList<>();    
for (Integer lobId: collection ) {
     ..
     if (someCondition) {
         tempCollection.add(something); 
         break; 
     }
}

collection.addAll(tempCollection);
like image 168
jax Avatar answered Sep 27 '22 23:09

jax