在 Java 中使用 Iterable<T>
和 Collection<T>
的考虑是什么?
例如,考虑实现一个主要关注包含 Foo
集合和一些相关元数据的类型。此类型的构造函数允许一次性初始化对象列表。(元数据可以稍后设置。)这个构造函数应该接受什么类型?Iterable<Foo>
还是 Collection<Foo>
?
这个决定的考虑因素是什么?
遵循由库类型设定的模式,如 ArrayList
(它可以从任何 Collection
初始化,但是 没有和 Iterable
)将导致我使用 Collection<Foo>
。
但是为什么不接受 Iterable<Foo>
,因为这已经足够满足初始化的需要了?为什么要求消费者提供更高级别的功能(Collection
) ,而不是严格必要的功能(Iterable
) ?