Why does Iterator define the remove() operation?-Collection of common programming errors

There are situations where you want to be able to remove elements using the iterator because it is the most efficient way to do it. For example, when traversing a linked data structure (e.g. a linked list), removing using the iterator is an O(1) operation … compared to O(N) via the List.remove() operations.

And of course, many collections are designed so that modifying the collection during a collection by any other means than Iterator.remove() will result in a ConcurrentModificationException.

If you have a situation where you don’t want to allow modification via a collection iterator, wrapping it using Collection.unmodifiableXxxx and using it’s iterator will have the desired effect. Alternatively, I think that Apache Commons provides a simple unmodifiable iterator wrapper.

By the way IEnumerable suffers from the same “smell” as Iterator. Take a look at the reset() method. I was also curious as to how the C# LinkedList class deals with the O(N) remove problem. It appears that it does this by exposing the internals of the list … in the form of the First and Last properties whose values are LinkedListNode references. That violates another design principle … and is (IMO) far more dangerous than Iterator.remove().