为什么迭代器方法同时存在于Iterable和Collection接口中?

Gau*_*agi 6 java collections iterable

Iterable接口具有以下方法:

 Iterator<T> iterator();
Run Code Online (Sandbox Code Playgroud)

Collection接口扩展Iterable,同时也宣布了同样的方法。

我怀疑在设计Java集合时需要两次将相同的方法声明放入两次吗?

luk*_*302 5

一个可能的原因可能是添加的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
 */
Run Code Online (Sandbox Code Playgroud)

Iterable“仅”是:

/**
 * Returns an iterator over elements of type {@code T}.
 *
 * @return an Iterator.
 */
Run Code Online (Sandbox Code Playgroud)


Tho*_*ger 3

主要原因是Java 5。

java.util.Collection及其iterator()方法java.util.Iterator自 Java 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 循环。

  • 即便如此,我喜欢历史推理,我不明白为什么*他们*在“他们使 java.util.Collection 扩展 java.lang.Iterable”时不从“Collection”中删除该方法? (2认同)