Quantcast
Channel: In detail, how does the 'for each' loop work in Java? - Stack Overflow
Viewing all articles
Browse latest Browse all 30

Answer by Manohar for In detail, how does the 'for each' loop work in Java?

$
0
0

It adds beauty to your code by removing all the basic looping clutter. It gives a clean look to your code, justified below.

Normal for loop:

void cancelAll(Collection<TimerTask> list) {    for (Iterator<TimerTask> i = list.iterator(); i.hasNext();)         i.next().cancel();}

Using for-each:

void cancelAll(Collection<TimerTask> list) {    for (TimerTask t : list)        t.cancel();}

for-each is a construct over a collection that implements Iterator. Remember that, your collection should implement Iterator; otherwise you can't use it with for-each.

The following line is read as "for each TimerTask t in list."

for (TimerTask t : list)

There is less chance for errors in case of for-each. You don't have to worry about initializing the iterator or initializing the loop counter and terminating it (where there is scope for errors).


Viewing all articles
Browse latest Browse all 30

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>