HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

Calling remove in foreach loop in Java

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
javacallingremoveloopforeach

Problem

In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance:

List names = ....
for (String name : names) {
   // Do something
   names.remove(name).
}


As an addendum, is it legal to remove items that have not been iterated over yet? For instance,

//Assume that the names list as duplicate entries
List names = ....
for (String name : names) {
    // Do something
    while (names.remove(name));
}

Solution

To safely remove from a collection while iterating over it you should use an Iterator.

For example:

List names = ....
Iterator i = names.iterator();
while (i.hasNext()) {
   String s = i.next(); // must be called before you can call i.remove()
   // Do something
   i.remove();
}


From the Java Documentation :


The iterators returned by this class's iterator and listIterator
methods are fail-fast: if the list is structurally modified at any
time after the iterator is created, in any way except through the
iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException. Thus, in the face of concurrent
modification, the iterator fails quickly and cleanly, rather than
risking arbitrary, non-deterministic behavior at an undetermined time
in the future.

Perhaps what is unclear to many novices is the fact that iterating over a list using the for/foreach constructs implicitly creates an iterator which is necessarily inaccessible. This info can be found here

Code Snippets

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

Context

Stack Overflow Q#1196586, score: 1034

Revisions (0)

No revisions yet.