my favorite Java 5 change


I used Java 5 (with Eclipse 3.1) for the code I wrote last week to use as example for manifold, and there's no question: the enhanced for loop, combined with generics, rocks.

Aside from the basic difference of going from (Note, use of an inline iterator is also common):

//strings is an ArrayList
for (int i=0; i<strings.size(); ++i) {
String s = (String) strings.get(i);
//do something with s
}
to
for (String s : strings) {
//do something with s
}
there's also the cooler use of it to iterate over the contents of a HashMap, so instead of doing
HashMap m = new HashMap();
//...
//fill the map with String, Vector values
//...
Iterator it = m.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
String value = (Vector) m.get(key);
}
you can do
HashMap m = new HashMap();
//...
//fill the map with String, Vector values
//...
for (String key : m.keySet()) {
Vector value = m.get(key);
}
Which is much more concise, and clear IMO. Very cool.

Categories: soft.dev
Posted by diego on December 20 2004 at 6:19 PM
Comments (please see the comments & trackback policy).

Why not use the entry set?
(you avoid to lookup the value)

HashMap m = new HashMap();
//...
//fill the map with String, Vector values
//...
Iterator it = m.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
Vector value = (Vector) entry.getValue();
}


Or using Java 5:

HashMap m = new HashMap();
//...
//fill the map with String, Vector values
//...
for (Map.Entry entry : m.entrySet()) {
String key = entry.getKey();
Vector value = entry.getValue();
}


Posted by: Juan Cruz Nores at December 20, 2004 7:05 PM

Indeed. :) I was going to mention that and I forgot. I don't use that because it sounds slightly "dirty" to me, dependent on the internal structure of the hash which is not something that is technically exposed. But it's also a good option. :)

Posted by: Diego at December 20, 2004 8:33 PM

Seems like something ate your type declarations in the HashMap<String, Vector> declarations ;)

Posted by: Tom Klaasen at December 21, 2004 9:49 AM

I'm pretty sure entrySet isn't dependent on the internal structure of HashMap. I think Map.Entry objects are created for each entry when you call entrySet.

Posted by: Keith Lea at December 21, 2004 10:57 PM

Isn't this Java getting C#'s foreach()?

BTW I'm not saying stole (after all C# copies many ideas from Java).

Still it does save a few lines of code.

Posted by: Mark Levison at December 21, 2004 11:11 PM

Copyright © Diego Doval 2002-2007.
Powered by
Movable Type 3.35