Tuesday, February 03, 2009

For-Each Loop

for(Type type : types) {
... type ...
}

The For-Each loop makes Java code much more beautiful and clean than before. We shall use it any time we can.

Several exceptions,
  1. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering.
  2. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it.
  3. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.

No comments: