Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not Iterator have add method whereas List Iterator has one in Java?

Tags:

java

Can any one guide why is it design like this.

Iterator does not have add() method but List Iterator has one in Java.

like image 926
Learner Avatar asked Sep 09 '14 12:09

Learner


People also ask

Why iterator does not have ADD method 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 ).

Does iterator have an add method?

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.

What is the difference between iterator and list iterator in Java?

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.

Why ListIterator has add () method?

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.


1 Answers

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.

like image 165
Eran Avatar answered Nov 15 '22 02:11

Eran