Collection - Iterator.remove() vs Collection.remove()

NINCOMPOOP picture NINCOMPOOP · Jan 7, 2013 · Viewed 9.1k times · Source

As per Sun ,

"Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress."

I have two questions :

  1. What makes this operation "Iterator.remove()" stable than the others ?
  2. Why did they provide a "Collection.remove()" method if it will not be useful in most of the use-cases?

Answer

NPE picture NPE · Jan 7, 2013

First of all, Collection.remove() is very useful. It is applicable in a lot of use cases, probably more so than Iterator.remove().

However, the latter solves one specific problem: it allows you to modify the collection while iterating over it.

The problem solved by Iterator.remove() is illustrated below:

    List<Integer> l = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4));
    for (int el : l) {
        if (el < 3) {
            l.remove(el);
        }
    }

This code is invalid since l.remove() is called during iteration over l.

The following is the correct way to write it:

    Iterator<Integer> it = l.iterator();
    while (it.hasNext()) {
        int el = it.next();
        if (el < 3) {
            it.remove();
        }
    }