CALLING REMOVE IN FOREACH LOOP IN JAVA

sandy taylor

Total Post:46

Points:324
Posted by  sandy taylor
 793  View(s)
Ratings:
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));
}
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Calling remove in foreach loop in Java

    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!