Home >Java >javaTutorial >How to Safely Remove Elements from a Java Collection While Iterating?
Safely Removing Elements during Iteration in Java
Q: Is it permissible to remove elements from a collection while iterating over it using a foreach loop in Java?
A: Using a foreach loop for removal is not advisable. It can result in unexpected behavior as the underlying iterator is not exposed and directly accessible for modification.
Example:
List<String> names = .... for (String name : names) { // Do something names.remove(name). }
This code may fail with a java.util.ConcurrentModificationException as the remove operation modifies the collection underneath while the foreach loop is in progress.
Q: Can we remove items that have not been iterated over yet?
A: No. Removing elements not yet processed in the loop can lead to an "index out of bounds" error. Example:
//Assume that the names list as duplicate entries List<String> names = .... for (String name : names) { // Do something while (names.remove(name)); }
To safely remove elements while iterating, an Iterator should be used:
List<String> names = .... Iterator<String> i = names.iterator(); while (i.hasNext()) { String s = i.next(); // must be called before you can call i.remove() // Do something i.remove(); }
The Java documentation emphasizes that iterators returned by the iterator and listIterator methods are "fail-fast." Any structural modifications to the list outside the iterator's remove or add methods will result in a ConcurrentModificationException.
The above is the detailed content of How to Safely Remove Elements from a Java Collection While Iterating?. For more information, please follow other related articles on the PHP Chinese website!