Java:为什么Collection.addAll不能接受Iterables?
我想知道为什么 Collection.addAll()
方法只接受其他 Collection
而不是 Iterable
。这是为什么?
对于 Iterable 是否有类似的方法?
I wonder why the Collection.addAll()
method only accepts other Collection
s but not Iterable
s. Why is that?
Any similar method to do that for Iterable
s?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
大概是因为
Collection
接口是在 Java 1.2 中引入的,而Iterable
仅在 1.5 中出现,并且更改接口会破坏所有现有的实现。Presumably because the
Collection
interface was introduced in Java 1.2 whereasIterable
appeared only in 1.5, and changing the interface would break all existing implementations.如有疑问,请务必检查 Guava(或 Commons):
When in doubt, always check Guava (or Commons):
其他人广泛回答了“为什么”。
在 Java 8 中,您不再需要
addAll
:Others have answered the "why" extensively.
In Java 8 you don't need
addAll
any more:基本上是因为
Iterable
可能永远不会结束(即hasNext()
永远返回 true)。另外,为了保持一致性,您可能认为
Collection
可以添加另一个集合的所有元素,但是Iterable
不一定是一个集合(它可以是任何东西,比如例如ResultSet
包装器)。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, anIterable
is not necesarily a collection (it may be anything, like the aResultSet
wrapper for instance).核心 JDK 中有很多东西不能像普通的 Iterables 一样工作得那么好。我建议使用 Guava 来克服许多这些缺点。
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.