foreach in Java 1.5

In: Java

13 Aug 2003

Joshua Bloch and Neal Gafter’s recent JavaLive chat further talks on generics and typesafe enums, 2 of the more significant new language features in the Java 1.5. There is interesting discussion on generics especially.

My favorite though is the enhanced for loop which is similar to the foreach construct in languages like PHP and Python.

The following example reads “for each Object in the Collection C…”:


void displayAll(Collection c) {
for (Object o : c)
((String)o).display();
}

I’ve always found the Java (and C/C++) for-loop idiom to be overly wordy and reduces code legibility, so this is a welcome addition.

Related links:
Previous interview with Joshua Bloch

5 Responses to foreach in Java 1.5

Avatar

Zohar

August 13th, 2003 at 6pm

Hmmmm

void displayAll(Collection c) {
for (String s : c)
s.display();
}

Avatar

Zohar

August 13th, 2003 at 6pm

The blody thing striped the generics bit :-)

should read :

void displayAll(Collection<String> c) {
for (String s : c)
s.display();
}

Avatar

Rob

October 10th, 2003 at 10pm

One of the few things I liked about C# over Java was the foreach statement.

I wonder if this new syntax will handle Collections, arrays, and Iterators, similar to the way C#’s foreach handles anything that can be iterated over.

I’m very glad to see Java adopt a new for loop, and I’ll be quite happy if it just handles Collections.

And, Zohar, I hope you’re not implying that the String tag you added in the method signature is a requirement. That would be counterproductive. What is that, anyway?

Avatar

Dave78

March 11th, 2004 at 4am

the “tag” you refer to: “”

it’s purpose is to make templated collections, new in 1.5. Very nice because it is more type safe by catching insertion type mismatches at compiletime rather than at runtime. i.e. you are guaranteed that the collection is filled with only what it says it is filled with. This has the added bonus of dropping a lot of overly verbose type casts. Since using only one type in a collection is the default case, it is nice to see the language better able to handle it.

Avatar

Dave78

March 11th, 2004 at 4am

doh! the tag in my previous post was interpreted as HTML and disappeared. I meant to have
tag : “< String >”