Now blogging at diego's weblog. See you over there!

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

Copyright © Diego Doval 2002-2011.
Powered by
Movable Type 4.37