为什么这么多方法使用 Collection 而不是 Iterable?

发布于 2024-11-06 19:51:19 字数 519 浏览 4 评论 0原文

使用 C#,我逐渐喜欢上了 IEnumerable 界面。在很多情况下,这就是您想要发出和接收的全部内容。此外,它在 .Net 库中很有用。例如,List 类上有一个构造函数,它采用 IEnumerable

我现在必须使用 Java,我自然想使用等效的 Iterable 接口。然而,我似乎并不能在任何地方使用它。一切似乎都在使用扩展的 Collection 接口。这是为什么呢?

例如,您有一个采用 CollectionArrayList 构造函数:

构造一个列表,其中包含指定集合的​​元素,按照集合迭代器返回的顺序排列。

为什么不直接采用 Iterable 来代替呢?

With C# I grew to love the IEnumerable<T> interface. There are a lot of cases where that's all you want to give out and take in. In addition it's useful in the .Net library. You have for example a constructor on the List<T> class which takes an IEnumerable<T>.

I have to work with Java at the moment, and I naturally wanted to use the equivalent Iterable<T> interface. However, it doesn't really seem like I can use it anywhere. Everything seems to be using the extended Collection<T> interface instead. Why is this?

As an example, you have the ArrayList<T> constructor which takes a Collection<T>:

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

Why not just take an Iterable<T> instead?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

倒数 2024-11-13 19:51:19

Iterable 仅在 Java 5 中添加。这意味着较旧的方法(其中大多数)使用集合。即使是可以采用 Iterable 的较新方法也没有使用它。 :(

我认为问题在于大多数 Iterable 都是集合。

Iterable was only added in Java 5. This means older methods (most of them) use collections. Even newer methods which could take Iterable haven't used it. :(

I think the problem is that most Iterable are Collections.

黑白记忆 2024-11-13 19:51:19

作为示例,您有一个接受 Collection 的 ArrayList 构造函数

具有可预测的大小是很好的,特别是。对于 ArrayList(它确实使用 toArray() 来构建其底层 Object[])

构造一个列表,其中包含指定集合的​​元素,按照集合迭代器返回的顺序排列。

可爱的sun懒得再次更新文档,它根本不使用迭代器;
事实上,我自己几乎从未阅读过这些文档,因为它们往往要么是误导性的,要么就是完全错误的。

此外,您还可以通过子类化 AbstractCollection(仅缺少易于实现的 size() 和 iterator())来轻松地将 Iterable 适配到 Collection 中,

引入 Iterable 主要是为了符合 foreach 构造。

As an example, you have the ArrayList constructor which takes a Collection

Having predictable size is good, esp. for an ArrayList (it does use toArray() to build its underlying Object[])

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

Lovely sun were lazy to update the docs again, it doesn't use iterator at all;
Actually myself I almost never read the docs since they often tend to be either mislead or just plain wrong.

Also you can easily fit an Iterable to a Collection by subclassing AbstractCollection (which lacks only size() and iterator() readily implemented)

Iterable was introduced mostly to conform foreach construct.

陈年往事 2024-11-13 19:51:19

因为他们希望允许对集合做更多的事情而不仅仅是迭代它?

Because they want to allow doing more with the collection than just iterating over it?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文