0 votes
1 view
in Java by (2.4k points)

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

List<String> 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<String> 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<String> names = ....

for (String name : names) {

    // Do something

    while (names.remove(name));

}

1 Answer

0 votes
by (21.1k points)

Use iterator to safely remove from a collection while iterating over it:

Example:

List<String> names = ....

Iterator<String> i = names.iterator();

while (i.hasNext()) {

   String s = i.next(); // need to be called before you can call i.remove()

   // your work

   i.remove();

}

This is stated in Java Documentation:

The iterator returned by this class's iterator and listIterator methods is fail-fast, meaning, if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's 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.

Possibly what is confusing to many beginners is the fact that iterating over a list using the for/foreach constructs inevitably builds an iterator which is necessarily inaccessible. You can read about it here

...