Home >Java >javaTutorial >How to Avoid a ConcurrentModificationException When Iterating and Modifying an ArrayList?

How to Avoid a ConcurrentModificationException When Iterating and Modifying an ArrayList?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 08:21:28803browse

How to Avoid a ConcurrentModificationException When Iterating and Modifying an ArrayList?

ConcurrentModificationException occurs when an ArrayList is traversed (iterated over) and modified at the same time. This article explores the best practices for handling this exception, outlining alternative approaches.

Avoiding Concurrent Modification Exception

To prevent the exception from occurring, two options are available:

  1. Create a List of Values to Remove: While iterating, add values that need to be removed to a separate list. Once the iteration is complete, call the "removeAll" method on the original list.
  2. Use Iterator's Remove Method: Instead of modifying the ArrayList directly within the loop, use the "remove" method of the iterator itself. This requires using the traditional for loop instead of the enhanced for loop.

Example of Iterator's Remove Method:

Consider the scenario of removing strings with a length greater than 5 from an ArrayList:

<code class="java">List<String> list = new ArrayList<>();
...
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
    String value = iterator.next();
    if (value.length() > 5) {
        iterator.remove();
    }
}</code>

In this example, the iterator's "remove" method is employed to safely modify the original list while iterating through it.

The above is the detailed content of How to Avoid a ConcurrentModificationException When Iterating and Modifying 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