So now I have a somewhat reasonable explanation:
Short version: Because the syntax also applies to arrays that don't have iterators.
If the syntax was designed around Iterator , as I suggested, it will not be compatible with arrays. Let me give you three options:
A) selected by Java developers:
Object[] array; for(Object o : array) { } Iterable<Object> list; for(Object o : list) { } Iterator<Object> iter; while(iter.hasNext()) { Object o = iter.next(); }
It behaves the same and is very consistent between arrays and collections. Iterators, however, should use the classic iteration style (which, at least, does not cause errors).
B) allow arrays and Iterators :
Object[] array; for(Object o : array) { } Iterable<Object> list; for(Object o : list.iterator()) { } Iterator<Object> iter; for(Object o : iter) { }
Arrays and collections are now incompatible; but arrays and ArrayList are very closely related and should behave the same. Now, if at any moment the language expands to make, for example, arrays implement Iterable , it becomes inconsistent.
C) allow all three:
Object[] array; for(Object o : array) { } Iterable<Object> list; for(Object o : list) { } Iterator<Object> iter; for(Object o : iter) { }
Now, if we find ourselves in unclear situations, when someone realizes both Iterable and Iterator (this is a for loop that should get a new iterator or iterate over the current one - it happens easily in tree structures!?!). Unfortunately, a simple tie-braker ala "Iterable beats Iterator" will not do: it unexpectedly introduces runtime and compile time difference and generic problems.
Now, unexpectedly, we need to pay attention to whether we want iterations over collections / iterators or arrays, and at that moment we got very few advantages due to a lot of confusion.
The "for everyone" method is very consistent in Java (A), it causes very few programming errors, and this allows a possible future change in the rotation of arrays into ordinary objects.
There is option D) , which will probably also work fine: for each for iterators. Preferably by adding the .iterator() method to primitive arrays:
Object[] array; for(Object o : array.iterator()) { } Iterable<Object> list; for(Object o : list.iterator()) { } Iterator<Object> iter; for(Object o : iter) { }
But this requires changes to the runtime, not just the compiler, and interruptions to backward compatibility. In addition, the above confusion is still present that
Iterator<Object> iter; for(Object o : iter) { } for(Object o : iter) { }
Only one repetition of data is performed.