Home > Java > javaTutorial > How to Avoid ConcurrentModificationException When Adding to an ArrayList During Iteration in Android?

How to Avoid ConcurrentModificationException When Adding to an ArrayList During Iteration in Android?

Barbara Streisand
Release: 2024-12-03 07:52:09
Original
265 people have browsed it

How to Avoid ConcurrentModificationException When Adding to an ArrayList During Iteration in Android?

ConcurrentModificationException while adding to ArrayList in Android

ConcurrentModificationException is commonly encountered while making modifications to a list being iterated over. This exception can arise in various scenarios, one of which is when altering an ArrayList using an Iterator.

In the provided code snippet, this issue manifests during an OnTouchEvent event when adding a new Element to the mElements ArrayList:

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

    // ...

    if(element.cFlag){
        mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
        element.cFlag = false;
    }
}
Copy after login

The ConcurrentModificationException is thrown because the list is being modified (by adding elements) while it is being iterated using the Iterator.

To address this issue, it is recommended to utilize a separate List to store the elements that need to be added during the iteration:

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

    // ...

    if (element.cFlag) {
        // Instead of adding elements directly to mElements, add them to thingsToBeAdded
        thingsToBeAdded.add(new Element("crack", getResources(), (int) touchX, (int) touchY));
        element.cFlag = false;
    }
}
mElements.addAll(thingsToBeAdded);
Copy after login

By using this approach, modifications to the original list can be deferred until after iterating over the elements, thereby avoiding the ConcurrentModificationException.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template