"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Avoid ConcurrentModificationException When Modifying an ArrayList During Iteration?

How to Avoid ConcurrentModificationException When Modifying an ArrayList During Iteration?

Posted on 2025-03-22
Browse:146

How to Avoid ConcurrentModificationException When Modifying an ArrayList During Iteration?

ConcurrentModificationException while Modifying an ArrayList During Iteration

The reported exception is a ConcurrentModificationException, originating from the attempt to modify an ArrayList, mElements, while iterating over it.

Inside an OnTouchEvent handler, there's a loop iterating over mElements using an Iterator to check for specific conditions:

for (Iterator it = mElements.iterator(); it.hasNext();){
    Element element = it.next();

    // Check element's position and other conditions...

    if(element.cFlag){
        mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY)); // ConcurrentModificationException occurs here
        element.cFlag = false;
    }
}

However, modifying the ArrayList (by adding a new element) while iterating over it using an Iterator can cause a ConcurrentModificationException.

Solution:

To avoid this exception, one option is to create a separate list to store elements that need to be added and append those to the main list after completing the iteration:

List thingsToBeAdd = new ArrayList();
for(Iterator it = mElements.iterator(); it.hasNext();) {
    Element element = it.next();

    // Check element's position and other conditions...

    if(element.cFlag){
        // Store the new element in a separate list for later addition
        thingsToBeAdd.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
        element.cFlag = false;
    }
}

// Add all elements from the temporary list to the main list
mElements.addAll(thingsToBeAdd );

Alternative Approach:

Another approach is to use an enhanced for-each loop, which iterates over a copy of the list, preventing ConcurrentModificationException:

for (Element element : mElements) {

    // Check element's position and other conditions...

    if(element.cFlag){
        mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY)); // No ConcurrentModificationException
        element.cFlag = false;
    }
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3