Can any one guide why is it design like this.
Iterator does not have add() method but List Iterator has one in Java.
The sole purpose of an Iterator is to enumerate through a collection. All collections contain the add() method to serve your purpose. There would be no point in adding to an Iterator because the collection may or may not be ordered (in the case of a HashSet ).
The . add() method adds an item to the underlying collection of a ListIterator object. This method adds the item before the next element that would be returned by the . next() method.
An Iterator is an interface in Java and we can traverse the elements of a list in a forward direction whereas a ListIterator is an interface that extends the Iterator interface and we can traverse the elements in both forward and backward directions.
The add() method of ListIterator interface is used to insert the given element into the specified list. The element is inserted automatically before the next element may return by next() method.
My original thought was, like some of the other answers, to say that Iterator
might be implemented by an immutable class. However, that answer is not enough, since Iterator does have a delete
method (even though it doesn't have to be supported in all implementations).
I think a better reason for not having insert
in Iterator
is that it would have a meaning only in ordered data structures (such as lists). For example, there is no meaning to adding an element to a Set
via an iterator of that Set
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With