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

How to Avoid ConcurrentModificationException When Removing Elements from an ArrayList?

Barbara Streisand
Release: 2024-10-30 20:34:30
Original
359 people have browsed it

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();
    }
}
Copy after login

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!

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