Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the need to have listIterator() and iterator() in the list interface in Java?

The List interface has two methods listIterator() and iterator(). why both of these are needed.

From the docs:

Iterator<E> iterator()

Returns an iterator over the elements in this list in proper sequence.

ListIterator<E> listIterator()

Returns a list iterator over the elements in this list (in proper sequence).

    ListIterator<E> listIterator(int index)

    Returns a list iterator over the elements in this list (in proper sequence), starting at the 
specified position in the list. The specified index indicates the first element that would be 
returned by an initial call to next. An initial call to previous would return the element with the 
specified index minus one.

so basically, ListIterator() has this additional methods to get previous and next elements while Iterator() has only next elements. Is this only for this purpose, there is another ListIterator() interface and listiterator() method in List inteface

like image 346
brain storm Avatar asked Nov 05 '13 21:11

brain storm


2 Answers

Specifically they are both required because List is a type of Iterable which specifies an Iterator iterator() method.

Now List could have simply overridden the iterator() method in Iterable to declare a return type of ListIterator which is type of Iterator (thus satisfying the contract). Why this was not done is probably a design decision.

EDIT: @ajb pointed out in a comment that covariant return types were added in Java SE 5 after the List interface was created. This explains why List has both methods, as iterator() return type could not be narrowed to ListIterator in Java 1.2.

like image 40
Dev Avatar answered Sep 21 '22 02:09

Dev


Since Java 5 it is simply possible to override a method with a more specific return type (called covariant return type). But ListIterator has been introduced with Java 1.2. To avoid casts on usage of iterator() there has to be a new method.

The API could not have been changed from Java 5 on because that would have broken all implementations of List which do not declare iterator() returning ListIterator also if most implementations return a ListIterator instance in real.

A similar dilemma is Enumeration and Iterator. Nowadays Iterator would extend Enumeration and simply add the remove() method. Or better Iterator would have replaced Enumeration and a ModifiableIterator with an additional remove() would have been added.

like image 97
Arne Burmeister Avatar answered Sep 23 '22 02:09

Arne Burmeister