
[英]Why does AbstractCollection implement both Iterable and Collection?
[英]Why is the iterator method present in both Iterable and Collection interfaces? [duplicate]
这个问题在这里已有答案:
Iterable
接口具有以下方法:
Iterator<T> iterator();
Collection
接口扩展了Iterable
,它也声明了相同的方法。
我怀疑在设计Java集合时需要两次放置相同的方法声明吗?
一个可能的原因可能是添加的javadoc清楚地说明了该方法正在做什么。 对于Collection
它是:
/**
* 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
*/
而对于Iterable
它“only”是:
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
重新定义接口方法是一种常见的做法,它允许子接口细化超级接口定义的契约。
Iterable
的iterator()
返回某种类型元素的迭代器。
Collection
的iterator()
返回Collection
的元素上的迭代器,而不保证顺序。
List
的iterator()
以适当的顺序返回List
元素的迭代器。
这意味着如果你实现了一些实现Collection
类的iterator()
方法,你应该遵循Collection
的iterator()
的契约,它比Iterable
的iterator()
契约更具体。 如果你的类也实现了List
,你应该遵循List
的iterator()
更具体的契约。
主要原因是Java 5。
java.util.Collection
与它的iterator()
方法和java.util.Iterator
自爪哇1.2存在。
当他们想引入Java 5中增强的for循环(一个for (String s: ...) {}
他们需要一种方法来创建一个java.util.Iterator
从一个没有实现的类java.util.Collection
决定引入一个新的接口java.lang.Iterable
,它可以由所有想要支持增强的for循环的类实现。
为了使现有的java.util.Collection
及其所有的后代接口和类与增强的for循环兼容,他们使java.util.Collection
扩展了java.lang.Iterable
。
因此,两个接口都有一个方法iterator()
- java.util.Collection
因为它是“第一个”, java.lang.Iterable
用于支持增强的for循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.