For a collection class that has an Iterator, instead of
for (Iterator iter = names.iterator(); iter.hasNext(); ) {
String name = (String) iter.next();
// do something with name
}
you can now say
for (String name: names)
// do something with name
Notes:
When to Use
• Any time you can!
─ Really beautifies code
• You can’t use for-each for these cases
─ Removing elements when iterating
─ Modifying the current element in an array or collection
─ Iterating over multiple collections or arrays
─ Iterating backward through the elements