Java:迭代器/可迭代的 Collections.list
为什么java.util.Collections.list
仅适用于Enumeration
而不适用于Iterator
(或Iterable
)?或者为什么 Iterator
(或 Iterable
)没有重载此函数?还有其他方法可以做到这一点吗?有什么原因吗?
Why is java.util.Collections.list
only for Enumeration
but not for Iterator
(or Iterable
)? Or why is there not an overload of this function for Iterator
(or Iterable
)? Is there any other method which does that? Is there any reason why that is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
还没有人真正回答这个问题,所以我在这里:
当它被引入时,可能还没有
Iterable
。现在,它已经过时了(大多数Collection
实现的构造函数都提供相同的东西)并且只是为了向后兼容而保留下来。Noone really answered it yet, so here I go:
When it what introduced, there probably was no
Iterable
yet. Now, it is obsolete (constructors of mostCollection
implementations provide the same thing) and just stays there for backward compatibility.来自 JavaDoc:
如果您有一个 Collection 并且想要基于该集合创建新的 List,您可以使用构造函数或
addAll()
方法。这个方法有点像集合框架提供的适配器。对于自定义迭代,您可以使用增强的 for 循环将迭代器返回的元素复制到现有列表。
From the JavaDoc:
If you have a Collection and want to make new List based on that collection, you can use constructors or the
addAll()
method. This method is somthing like an adapter provided by the collections framework.For custom iterables you can use the enhanced for loop to copy the elements returnd by an iterator to an existing list.
其目的是提供返回枚举的旧 API 和需要集合的新 API 之间的互操作性
it's purpose is to provide interoperability between legacy APIs that return enumerations and new APIs that require collections