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.




Michael Phelps is a tremendous athlete. Jarrod Shoemaker is also a tremendous athlete. So why is Phelps is able to compete for 8 medals and get the attention and sponsorships, while Shoemaker can win but one, and you’ve probably never heard of him or know what sport he plays. Do we really need separate medals for the 100m and 200m and 400m butterfly, and yet 2 more for the 100m and 200m freestyle, and more for the individual medley, the breaststroke, and so on. There’s one medal for running 200m. There isn’t a separate medal for running it uphill, or backwards, or with a hat on. There’s only one medal for the grueling triathalon (Shoemaker’s sport), for the entire basketball/softball/soccer tournaments, yet some sports pile them on the same people because the events simply aren’t differentiated enough.



