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
)?