Home >Java >javaTutorial >How to Avoid ConcurrentModificationException When Modifying an ArrayList During Iteration?

How to Avoid ConcurrentModificationException When Modifying an ArrayList During Iteration?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 20:25:13989browse

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<Element> 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<Element> thingsToBeAdd = new ArrayList<Element>();
for(Iterator<Element> 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;
    }
}

The above is the detailed content of How to Avoid ConcurrentModificationException When Modifying an ArrayList During Iteration?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn