Home > Java > javaTutorial > How to Avoid ConcurrentModificationException When Removing Elements from an ArrayList During Iteration?

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

Barbara Streisand
Release: 2024-10-28 03:18:30
Original
1063 people have browsed it

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.

<code class="java">ArrayList<A> valuesToRemove = new ArrayList<>();

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

abc.removeAll(valuesToRemove);</code>
Copy after login

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.

<code class="java">for (Iterator<A> iterator = abc.iterator(); iterator.hasNext();) {
    A a = iterator.next();
    if (a.shouldBeRemoved()) {
        iterator.remove();
    }
}</code>
Copy after login

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

The above is the detailed content of How to Avoid ConcurrentModificationException When Removing Elements from an ArrayList During Iteration?. 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