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?
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.
*/
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()
.
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