Home >Java >javaTutorial >How to Safely Remove Elements from a Java List During Iteration?

How to Safely Remove Elements from a Java List During Iteration?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-31 18:42:10560browse

How to Safely Remove Elements from a Java List During Iteration?

Calling remove in a Foreach Loop in Java

Iterating Safely Using Iterators

Modifying a collection while iterating through it using a foreach loop can lead to errors. To safely remove elements during iteration, use an explicit Iterator.

List<String> names = ...
Iterator<String> i = names.iterator();
while (i.hasNext()) {
    String s = i.next();
    if (...) {
        i.remove();
    }
}

Concurrent Modification Exception

Without using an Iterator, the code will fail with a ConcurrentModificationException if the collection is modified during iteration. The explicit Iterator ensures that the changes are tracked and reflected in the underlying collection.

Note on Nested Removal

In the provided example, the inner while loop continues to remove the same element until it no longer exists. While technically legal, it's generally considered poor practice unless there's a very specific reason.

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