Albert
Albert

Reputation: 68350

Java: why does Collection.addAll can not accept Iterables?

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?

Upvotes: 45

Views: 11674

Answers (5)

Michael Brewer-Davis
Michael Brewer-Davis

Reputation: 14296

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

Upvotes: 35

Jon Skeet
Jon Skeet

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

OscarRyz
OscarRyz

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

TWiStErRob
TWiStErRob

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

Michael Borgwardt
Michael Borgwardt

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

Related Questions