Home > DeveloperSection > Forums > Calling remove in foreach loop in Java
sandy taylor
sandy taylor

Total Post:46

Points:324
Posted on    September-03-2015 12:05 AM

 Java Java  Collection 
Ratings:


 1 Reply(s)
 436  View(s)
Rate this:
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
    while (names.remove(name));
}


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    September-03-2015 6:07 AM

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

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

Don't want to miss updates? Please click the below button!

Follow MindStick