Home >Java >javaTutorial >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:
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!