Learnitweb

Why there is no method like Iterator.add() to add elements to the collection?

The purpose of iterator is to traverse elements of collection. An Iterable object might be immutable. In this case iterator add method will be trying to insert an element in an immutable collection.

Consider the case of HashSet and TreeSet. There is no prediction in general whether the insert will be “after” or “before” the current position of the iterator. So we can not predict whether the iterator will still traverse elements that were inserted during iteration. Thus add() method would give rise to unpredictable behavior.

Adding add() operation to Iterator can potentially result in an operation that is not supported by underlying collection. However in case of remove(), it would depend on the value passed.