Friday, February 9, 2007

Love your loops and let them love you

I'm not a language freek, but I can appreciate an improviment when I see it. One of the new features in Java 5 is their new and improved for loop. Lets say I want to iterator over a Vector of Strings.


Vector list = new Vector();


The old way (pre java 5)

Iterator<> iterator = list.iterator();
while (iterator.hasNext())
{
String s = iterator.next();
System.out.println(s);
}


And the new way (Java 5+)

for (String s : list)
{
System.out.println(s);
}


Enjoy!


UPDATE: I just noted that my collection generics was removed by blogger's posting thingy. Weird! Just so everyone knows, I was using Java 5 generics on the vector to strongly type it with Strings.

No comments: