"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 Removing Elements from an ArrayList During Iteration?

How to Avoid ConcurrentModificationException When Removing Elements from an ArrayList During Iteration?

Published on 2024-11-08
Browse:205

How to Avoid ConcurrentModificationException When Removing Elements from an ArrayList During Iteration?

How to Handle ConcurrentModificationException When Modifying an ArrayList While Iterating

When iterating through an ArrayList, attempting to remove elements during the iteration can result in a java.util.ConcurrentModificationException. This occurs due to the ArrayList's fail-fast mechanism, which detects any changes to the list's structure during iteration and throws the exception to prevent unexpected results.

To resolve this issue, there are two primary approaches to consider:

Option 1: Create a List of Values to Remove

This approach involves identifying the elements to be removed within the loop and adding them to a separate list. Once the iteration is complete, remove all the elements from the original list using the removeAll() method.

ArrayList valuesToRemove = new ArrayList();

for (A a : abc) {
    if (a.shouldBeRemoved()) {
        valuesToRemove.add(a);
    }
}

abc.removeAll(valuesToRemove);

Option 2: Use Iterator Remove

Alternatively, you can utilize the iterator's own remove() method. However, note that this approach requires using the traditional for loop rather than the enhanced for loop.

for (Iterator iterator = abc.iterator(); iterator.hasNext();) {
    A a = iterator.next();
    if (a.shouldBeRemoved()) {
        iterator.remove();
    }
}

By implementing one of these approaches, you can avoid the ConcurrentModificationException while effectively modifying your ArrayList during iteration.

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