I read Why is Java's Iterator not an Iterable? and Why aren't Enumerations Iterable?, but I still don’t understand why this:
void foo(Iterator<X> it) {
for (X x : it) {
bar(x);
baz(x);
}
}
was not made possible. In other words, unless I’m missing something, the above could have been nice and valid syntactic sugar for:
void foo(Iterator<X> it) {
for (X x; it.hasNext();) {
x = it.next();
bar(x);
baz(x);
}
}
I can see several reasons:
Iterators are not reusable, so a for/each would consume the iterator – not incorrect behavior, perhaps, but unintuitive to those who don’t know how the for/each is desugared.Iterators don’t appear “naked” in code all that often so it would be complicating the JLS with little gain (the for/each construct is bad enough as it is, working on bothIterables and arrays).Iterablesutility class, analogous toCollectionsandArrays, is beyond me, though.)I seem to recall that the JLS can only reference things injava.lang[citation needed], so they’d have to create anIteratorinterface injava.langwhichjava.util.Iteratorextends without adding anything to. Now we have two functionally equivalent iterator interfaces. 50% of the new code using naked iterators will choose thejava.langversion, the rest use the one injava.util. Chaos ensues, compatibility problems abound, etc.I think points 1-3 are very much in line with how the Java language design philosophy seems to go: Don’t surprise newcomers, don’t complicate the spec if it doesn’t have a clear gain that overshadows the costs, and don’t do with a language feature what can be done with a library.
The same arguments would explain why
java.util.Enumerationisn’tIterable, too.