Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent Modification Exception : adding to an ArrayList

People also ask

How do I fix concurrent modification exception?

How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.

What happens when 2 threads try to modify an ArrayList?

There is no guaranteed behavior for what happens when add is called concurrently by two threads on ArrayList. However, it has been my experience that both objects have been added fine. Most of the thread safety issues related to lists deal with iteration while adding/removing.

Can we modify ArrayList while iterating?

ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.


ConcurrentModificationException occurs when you modify the list (by adding or removing elements) while traversing a list with Iterator.

Try

List<Element> thingsToBeAdd = new ArrayList<Element>();
for(Iterator<Element> it = mElements.iterator(); it.hasNext();) {
    Element element = it.next();
    if(...) {  
        //irrelevant stuff..
        if(element.cFlag){
            // mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
            thingsToBeAdd.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
            element.cFlag = false;
        }           
    }
}
mElements.addAll(thingsToBeAdd );

Also you should consider enhanced for each loop as Jon suggested.


I normally use something like this:

for (Element element : new ArrayList<Element>(mElements)) {
    ...
}

quick, clean and bug-free

another option is to use CopyOnWriteArrayList


You're not allowed to add an entry to a collection while you're iterating over it.

One option is to create a new List<Element> for new entries while you're iterating over mElements, and then add all the new ones to mElement afterwards (mElements.addAll(newElements)). Of course, that means you won't have executed the loop body for those new elements - is that a problem?

At the same time, I'd recommend that you update your code to use the enhanced for loop:

for (Element element : mElements) {
    ...
}

An indexed for loop should also work.

for (int i = 0; i < collection.size(); i++)