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

試著忘記壹切 提交于 2019-12-13 11:45:52

问题


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?


回答1:


The main reason is Java 5.

java.util.Collection with its iterator() method and java.util.Iterator exist since Java 1.2.

When they wanted to introduce the enhanced for loop in Java 5 (the one for (String s: ...) {}, they needed a way to create a java.util.Iterator from classes that do not implement java.util.Collection. The decision was made to introduce a new interface java.lang.Iterable that can be implemented by all classes that want to support the enhanced for loop.

To make the existing java.util.Collection and all it's descendent interfaces and classes compatible with the enhanced for loop, they made java.util.Collection extend java.lang.Iterable.

Therefore both interfaces have a method iterator() - java.util.Collection because it was the "first born", java.lang.Iterable for supporting the enhanced for loop.




回答2:


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.
 */



回答3:


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().



来源:https://stackoverflow.com/questions/51232366/why-is-the-iterator-method-present-in-both-iterable-and-collection-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!