Reputation: 68350
I wonder why the Collection.addAll()
method only accepts other Collection
s but not Iterable
s. Why is that?
Any similar method to do that for Iterable
s?
Upvotes: 45
Views: 11674
Reputation: 14296
When in doubt, always check Guava (or Commons):
Upvotes: 35
Reputation: 1503679
There are quite a few things in the core JDK which don't work as well with plain Iterables as they might. I'd recommend using Guava to overcome a lot of these shortcomings.
Upvotes: 3
Reputation: 199333
Basically because an Iterable
may never end (that is, hasNext()
return true forever).
Also, to keep congruency, you may think a Collection
may add all the elements of another collection, but, an Iterable
is not necesarily a collection (it may be anything, like the a ResultSet
wrapper for instance).
Upvotes: 11
Reputation: 46498
Others have answered the "why" extensively.
Any similar method to do that for Iterables?
In Java 8 you don't need addAll
any more:
Collection<X> coll = ...;
Iterable<X> it = ...;
it.forEach(coll::add); // coll.addAll(it);
Upvotes: 13
Reputation: 346536
Presumably because the Collection
interface was introduced in Java 1.2 whereas Iterable
appeared only in 1.5, and changing the interface would break all existing implementations.
Upvotes: 39