Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the iterator method present in both Iterable and Collection interfaces? [duplicate]

The Iterable interface has the method below:

 Iterator<T> iterator();

The Collection interface extends Iterable, and it also declares the same method.

I am doubtful what was the need of putting the same method declaration twice while designing Java collections?

like image 340
Gautam Tyagi Avatar asked Jul 08 '18 13:07

Gautam Tyagi


2 Answers

One possible reason may be the added javadoc making clear what the method is doing. For Collection it is:

/**
 * Returns an iterator over the elements in this collection.  There are no
 * guarantees concerning the order in which the elements are returned
 * (unless this collection is an instance of some class that provides a
 * guarantee).
 *
 * @return an <tt>Iterator</tt> over the elements in this collection
 */

while for Iterable it "only" is:

/**
 * Returns an iterator over elements of type {@code T}.
 *
 * @return an Iterator.
 */
like image 102
luk2302 Avatar answered Oct 19 '22 16:10

luk2302


Redefining interface methods is a common practice the allows the sub-interface to refine the contract defined by the super-interface.

Iterable's iterator() returns an iterator over elements of some type.

Collection's iterator() returns an iterator over the elements of the Collection, without guaranteeing order.

List's iterator() returns an iterator over the elements of the List in proper sequence.

This means that if you implement the iterator() method of some class that implements Collection, you should follow the contract of Collection's iterator(), which is more specific than Iterable's iterator() contract. If your class also implements List, you should follow the even more specific contract of List's iterator().

like image 4
Eran Avatar answered Oct 19 '22 16:10

Eran