Question

I wonder why the Collection.addAll() method only accepts other Collections but not Iterables. Why is that?

Any similar method to do that for Iterables?

Was it helpful?

Solution

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.

OTHER TIPS

When in doubt, always check Guava (or Commons):

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

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top