Why is an array not assignable to Iterable? Why is an array not assignable to Iterable? java java

Why is an array not assignable to Iterable?


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.)


The array is an Object, but its items might not be. The array might hold a primitive type like int, which Iterable can't cope with. At least that's what I reckon.


Arrays ought to support Iterable, they just don't, for the same reason that .NET arrays don't support an interface that allows readonly random access by position (there is no such interface defined as standard). Basically, frameworks often have annoying little gaps in them, which it's not worth anyone's time to fix. It wouldn't matter if we could fix them ourselves in some optimal way, but often we can't.

UPDATE: To be even-handed, I mentioned .NET arrays not supporting an interface that supports random access by position (see also my comment). But in .NET 4.5 that exact interface has been defined and is supported by arrays and the List<T> class:

IReadOnlyList<int> a = new[] {1, 2, 3, 4};IReadOnlyList<int> b = new List<int> { 1, 2, 3, 4 };

All is still not quite perfect because the mutable list interface IList<T> doesn't inherit IReadOnlyList<T>:

IList<int> c = new List<int> { 1, 2, 3, 4 };IReadOnlyList<int> d = c; // error

Maybe there is a possible backward compatibility gotcha with such a change.

If there's any progress on similar things in newer versions of Java, I'd be interested to know in the comments! :)