为什么数组不能分配给 Iterable? [英] Why is an array not assignable to Iterable?

查看:41
本文介绍了为什么数组不能分配给 Iterable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Java5 我们可以编写:

with Java5 we can write:

Foo[] foos = ...
for (Foo foo : foos) 

或者只是在 for 循环中使用 Iterable.这非常方便.

or just using an Iterable in the for loop. This is very handy.

但是,您不能像这样为可迭代编写通用方法:

However you can't write a generic method for iterable like this:

public void bar(Iterable<Foo> foos) { .. }

并使用数组调用它,因为它不是可迭代的:

and calling it with an array since it is not an Iterable:

Foo[] foos = { .. };
bar(foos);  // compile time error 

我想知道这个设计决定背后的原因.

I'm wondering about the reasons behind this design decision.

推荐答案

数组可以实现接口(Cloneablejava.io.Serializable).那么为什么不 Iterable 呢?我猜 Iterable 强制添加一个 iterator 方法,而数组不实现方法.char[] 甚至不会覆盖 toString.无论如何,引用数组应该被认为不太理想 - 使用 Lists.正如 dfa 评论的那样,Arrays.asList 会明确地为您进行转换.

Arrays can implement interfaces (Cloneable and java.io.Serializable). So why not Iterable? I guess Iterable forces adding an iterator method, and arrays don't implement methods. char[] doesn't even override toString. Anyway, arrays of references should be considered less than ideal - use Lists. As dfa comments, Arrays.asList will do the conversion for you, explicitly.

(话虽如此,您可以对数组调用clone.)

(Having said that, you can call clone on arrays.)

这篇关于为什么数组不能分配给 Iterable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆