foreach in Java 1.5

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 Comments & TrackBacks ()

Paper doll icon
Zohar's Gravatar

Hmmmm

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

Posted by: Zohar on August 13, 2003 6pm

Paper doll icon
Zohar's Gravatar

The blody thing striped the generics bit :-)

should read :

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

Posted by: Zohar on August 13, 2003 6pm

Paper doll icon
Rob's Gravatar

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?

Posted by: Rob on October 10, 2003 10pm

Paper doll icon
Dave78's Gravatar

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.

Posted by: Dave78 on March 11, 2004 4am

Paper doll icon
Dave78's Gravatar

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

Posted by: Dave78 on March 11, 2004 4am

You can subscribe to the RSS feed for comments on this post.

Sorry, this entry is no longer accepting comments. If you have something you really want to say, you can write me.