首页 > 解决方案 > 为什么 Iterable 和 Collection 接口中都存在迭代器方法?

问题描述

Iterable接口有以下方法:

 Iterator<T> iterator();

Collection接口 extends Iterable,它也声明了相同的方法。

我怀疑在设计 Java 集合时需要两次放置相同的方法声明是什么?

标签: javacollectionsiterable

解决方案


一个可能的原因可能是添加的 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它来说,“唯一”是:

/**
 * Returns an iterator over elements of type {@code T}.
 *
 * @return an Iterator.
 */

推荐阅读