Java Goofs: Enhanced For Loop

One of the “big deals” in Java 5 was the enhanced for-loop. Basically you could trim this:

for(int i=0;i<collection.size();i++) {
Object object = collection.get(i);
doSomething(object);
}

down to this:
for(Object object:collection) {
doSomething(object);
}

I don’t think such an improvement was really necessary, but combine this with generics and I have to admit your code does look a little cleaner, so I use them when possible. However, the for-loop is basically a half-implemented hack with two major goofs.

1. It works with anything implementing Iterable, and arrays. Despite working with anything Iterable, it does not work actual iterators, which seems just silly to me.
2. If the collection is null, it throws a NullPointerException. The only defense I’ve seen for this is that “a null collection is not the same as an empty collection”. Agreed, and those people clearly missed the point. The point was to clean up the code and now we have to add the same silly if(collection==null) around the loop. If your code really did need to know if the collection was null (e.g. lazy-loading), it’s going to check anyways, but this would save at least one more repetitive line if the loop just treated null as empty and did nothing.