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
Release: 2024-12-31 18:42:10
Original
554 people have browsed it

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

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!

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