Java – Why is an array not assignable to Iterable

javalanguage-design

with Java5 we can write:

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

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.

Best Answer

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.

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