Tuesday, February 16, 2010

For-Each and For Every

Year of the Tiger is here. I suddenly remember Java 1.5 has code name of Tiger.
Well, 1.5 is long while ago in the past (1.7 is coming soon). Of course, Sun codename does not follow the Chinese Zodiac.

One feature of 1.5 is the for-each loop, which dares to challege the "thou must have two semicolons in the for loop" dictated by C. Other language (such as C#) defines the keyword foreach. Well, C's for loop is "syntactic sugar" for the while loop. Now it is a different story. Note Sun's example. It is merely trying to confuse you by coding a while loop in the for-loop.
I never confuse myself and my code readers with ugly for loops. I only use for-loop when I need to loop something a specific number of times.

Instead of a for-loop, I would code a straight forward while loop.
Iterator i = i.iterator();
while (i.hasNext()) {
TimerTask t = i.next();
t.cancel();
}

and I always put {} around my blocks, even if there is only one statement.

The foreach loop reminds me of the "univeral quantification" in math, the upside down A, meaning "for every".

No comments: