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!