March 24th, 2007


Java 1.5's foreach() loop.

While I was researching mods to the JWS today, I found out something interesting about Java I didn't know before.

You know Perl's foreach() loop? Where you can say foreach (1 .. 100) { code; } and it'll automagically put each of the numbers from 1 to 100 into a loop variable, and then run the loop for each of them?

As of v1.5, Java has the same thing! Check out "2) Enhanced for loop" on this page. The example they give is:

int sum(int[] a)
  int result = 0;

  for (int i : a)    // Note our foreach usage here
    result += i;
  return result;

The "for (objName : Collection)" should be read as "for each item in the Collection, assign it to objName and do the statement(s) below on it. When all of the items in Collection have been processed, exit the loop". In addition to Collections, also note the enhanced for() works with arrays.

I've loved Perl's foreach() loop for a long time. It's cool to see it added to Java. However, some other web pages that I read said it can be slow sometimes. So use with caution. (Though I can't see why it would be slow, unless the underlying Collection is naturally slow. It's easy to see how the compiler can trivially re-phrase "for(i : collection) { stuff; }" into something like "myIter = collection.iterator(); while(myIter.hasNext()){ i =; stuff;1 }".)

1 "Stuff" is a technical term that only extremely skilled software engineers are allowed to use. ;]