Home  >  Article  >  Java  >  How to Avoid ConcurrentModificationException When Removing Elements from an ArrayList?

How to Avoid ConcurrentModificationException When Removing Elements from an ArrayList?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 20:34:30253browse

How to Avoid ConcurrentModificationException When Removing Elements from an ArrayList?

How to Overcome ConcurrentModificationException When Traversing and Removing Elements from an ArrayList

Iterating over an ArrayList while concurrently removing elements can trigger the infamous java.util.ConcurrentModificationException. To address this issue, there are several best practices to consider.

One approach is to create a separate list of elements you wish to remove. During loop iteration, add these elements to the secondary list, and once the iteration concludes, call the originalList.removeAll(valuesToRemove) method.

Alternatively, you can utilize the remove() method directly on the iterator. Note that this technique requires you to steer clear of the enhanced for loop. For instance, to eliminate strings exceeding a length of 5 from a list:

List<String> list = new ArrayList<String>();

for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
    String value = iterator.next();
    if (value.length() > 5) {
        iterator.remove();
    }
}

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