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

查看:83
本文介绍了为什么数组不能分配给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) { .. }

并使用数组调用它,因为它不是Iterable:

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.无论如何,应将引用数组视为不理想的数组-请使用List.如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天全站免登陆