Tuesday, 7 February 2012

How to use For each Loop

for loop:

void cancelAll(Collection<TimerTask> c) {
    for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
        i.next().cancel();
}
         The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error. Here is how the example looks with the for-each construct:
foreach loop:
void cancelAll(Collection<TimerTask> c) {
    for (TimerTask t : c)
        t.cancel();
}
        When you see the colon (:) read it as “in.” The loop above reads as “for each TimerTask t in c.” As you can see, the for-each construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don't have to declare the iterator, you don't have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need not concern yourself with it.)
Where for each loop should and should not be used:
  1. It is not usable for loops where you need to replace elements in a list or array as you traverse it.
  2. Finally, it is not usable for loops that must iterate over multiple collections in parallel.
Advantages of for each loop:
  1. Less error prone code.
  2. Improved readability
  3. Less number of variables to clean up

No comments:

Post a Comment