Home > Java > javaTutorial > How to Safely Remove Elements from an ArrayList During Concurrent Iteration in Java?

How to Safely Remove Elements from an ArrayList During Concurrent Iteration in Java?

Susan Sarandon
Release: 2024-10-29 10:14:03
Original
1022 people have browsed it

How to Safely Remove Elements from an ArrayList During Concurrent Iteration in Java?

Handling ConcurrentModificationException During Concurrent Iteration and Removal in ArrayList

In Java, iterating over a collection while concurrently modifying it can result in a java.util.ConcurrentModificationException. This exception arises when the collection's structure is altered during iteration due to add or remove operations.

To circumvent this issue when working with ArrayList, consider the following best practices:

  • Create a List of Elements to Remove:

    Maintain a separate list to track elements that need to be removed. Within the loop, simply add the elements to this list instead of removing them directly from the original list. Once the loop concludes, use ArrayList's removeAll() method to remove all the elements from the list.

  • Use Iterator's Remove Method:

    Employ the remove() method available on the iterator itself. Note that this requires abandoning the Java 8 enhanced for loop syntax for iterating through the list.

For example, if you aim to remove strings with a length greater than five from an ArrayList:

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

The above is the detailed content of How to Safely Remove Elements from an ArrayList During Concurrent Iteration in Java?. 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