我想知道为什么该Collection.addAll()
方法只接受其他Collection
s而不接受Iterable
s。这是为什么?
有没有类似的方法可以为Iterable
s 做到这一点?
大概是因为Collection
接口是在 Java 1.2 中引入的,而Iterable
只出现在 1.5 中,并且更改接口会破坏所有现有的实现。
如有疑问,请始终检查 Guava(或 Commons):
其他人已经广泛回答了“为什么”。
有没有类似的方法可以为 Iterables 做到这一点?
在 Java 8 中,您不再需要addAll
:
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.