43

我想知道为什么该Collection.addAll()方法只接受其他Collections而不接受Iterables。这是为什么?

有没有类似的方法可以为Iterables 做到这一点?

4

5 回答 5

39

大概是因为Collection接口是在 Java 1.2 中引入的,而Iterable只出现在 1.5 中,并且更改接口会破坏所有现有的实现。

于 2010-09-30T15:23:20.310 回答
33

如有疑问,请始终检查 Guava(或 Commons):

于 2010-09-30T15:25:10.207 回答
13

其他人已经广泛回答了“为什么”。

有没有类似的方法可以为 Iterables 做到这一点?

在 Java 8 中,您不再需要addAll

Collection<X> coll = ...;
Iterable<X> it = ...;
it.forEach(coll::add); // coll.addAll(it);
于 2016-08-03T12:04:28.367 回答
11

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

于 2010-09-30T15:23:56.863 回答
4

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.

于 2010-09-30T15:24:03.657 回答