何时应该接受可迭代的参数< T>与集合< T>在Java? [英] When should I accept a parameter of Iterable<T> vs. Collection<T> in Java?
问题描述
在Java中使用 Iterable< T>
与集合< T>
例如,考虑实现一个主要涉及包含 Foo
的集合的类型,以及一些关联的元数据。这种类型的构造函数允许对象列表的一次性初始化。 (元数据可以稍后设置。)这个构造函数接受什么类型? Iterable
或 Collection
?
遵循 ArrayList
它可以从任何 Collection
初始化,但不 Iterable
但是为什么不接受 Iterable< Foo> code>,因为这足以满足初始化需求?为什么要求消费者提供比严格必要的功能(
Collection
)更高的级别( Iterable
)? / p>
许多集合类型在 Iterable< T>
仅仅在1.5中引入) - 没有理由添加构造函数以接受 Iterable< T>
以及 集合< T>
但是改变现有构造函数将是一个突变。
我将使用 Iterable< T>
如果这允许你做你想要的一切。它对于调用者更灵活,特别是它允许您使用Google Java Collections(毫无疑问类似的库)相对轻松过滤/投影等。
What are the considerations of using Iterable<T>
vs. Collection<T>
in Java?
For example, consider implementing a type that is primarily concerned with containing a collection of Foo
s, and some associated metadata. The constructor of this type allows one-time initialisation of the object list. (The metadata can be set later.) What type should this constructor accept? Iterable<Foo>
, or Collection<Foo>
?
What are the considerations for this decision?
Following the pattern set forth by library types such as ArrayList
(which can be initialised from any Collection
, but not an Iterable
) would lead me to use Collection<Foo>
.
But why not accept Iterable<Foo>
, given that this is is sufficient for the initialisation needs? Why demand a higher level of functionality (Collection
) from the consumer, than what is strictly necessary (Iterable
)?
Many of the collection types existed before Iterable<T>
(which was only introduced in 1.5) - there was little reason to add a constructor to accept Iterable<T>
as well as Collection<T>
but changing the existing constructor would have been a breaking change.
Personally I would use Iterable<T>
if that allows you to do everything you want it to. It's more flexible for callers, and in particular it lets you do relatively easy filtering/projection/etc using the Google Java Collections (and no doubt similar libraries).
这篇关于何时应该接受可迭代的参数< T>与集合< T>在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!