views:

101

answers:

5

Hi,

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?

+6  A: 

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.

Michael Borgwardt
doh!!!... you're right, what was I thinking. .... deleting... and plus onening
OscarRyz
+2  A: 

Basically because an iterable may never en ( that is, getNext() 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 )

OscarRyz
Ah, your first point is a good one. I don't really understand what you mean by the second one and how it would affect the `addAll` method.
Albert
As for the second, an iterable is an interface, pretty much, anything, could implement it, and you may end up in the first situation, with an possible infinite loop.
OscarRyz
Not sure I agree. A Collection can be infinite in the same way as an Iterable, as you can construct a valid Collection as a wrapper around an Iterable.
GaryF
What would `size()` return?
OscarRyz
Nevermind, I've checked the doc, http://download.oracle.com/javase/6/docs/api/java/util/Collection.html#size%28%29 it should return Integer.MAX_VALUE
OscarRyz
+3  A: 

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.

Jon Skeet
A: 

Because not all Iterable objects are java.util.Collection.

E.g. java.sql.SQLException is iterable.

public class SQLException extends java.lang.Exception
                          implements Iterable<Throwable> {

How would collections interpret it? It wouldn't return a collection of it's parameterized type (of the collection).

The Elite Gentleman
+5  A: 

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

Michael Brewer-Davis
+1 for *When in doubt, always check Guava*. Most apache commons libs are great, but commons / collections is annoying because it doesn't support generics.
seanizer