Java’s new For-Each Loop

I was always a fan of the Visual Basic For-Each loop syntax. It was simple, anyone could read it and it made life very easy. I am so glad that Java now has a For-Each Loop! Your basic Java loop with an iterator looks something like this (using the new Generics syntax):

void cancelAll(Collection c) {
     for (Iterator i = c.iterator(); i.hasNext(); )       ;

Now with the new For-Each loop your code is extremely simplified, look at the same code but with the new syntax:

void cancelAll(Collection c) {    for (TimerTask t : c)        t.cancel();}

That is amazing. As the referenced web page states the new loop reads as “for each item of type TimerTask t in the c collection“. This is very streamlined and the best thing I like about this is Java is taking the good things from other languages and putting them into Java. This is what will make Java become even easier to use and more widely accepted in the programming world.

Reference: Java 1.5 Docs -> link

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.