Tuesday, July 31, 2007

Java 5 For-Each Loop

Java 5 has introduced a simplified for-each loop:

void cancelAll(Collection c) {
for (TimerTask t : c)
t.cancel();
}


Advantages:
- reduces clutter and opportunity for error with the iterator
- combines with generics for type safety
- avoids mistakes with nested iterations

Disadvantages
- hides the iterator therefore cannot remove or replace the current item

http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html

No comments: