JDK 1.5: simplified for loops 

Joined:
04/09/2007
Posts:
727

August 13, 2007 20:27:11    Last update: July 13, 2011 16:20:28
Sample code:
import java.util.*;

public class TestArrayList {
    public static void main(String[] args) {
        List<String> l = new ArrayList<String>();
        l.add("a");
        l.add("b");
        l.add("c");

        for (String s: l) {
            System.out.println(s.toUpperCase());
        }
    }
}


If you use iterators, the for loop is equivalent to:
for (Iterator<String> i = l.iterator(); i.hasNext(); ) {
        System.out.println(i.next().toUpperCase());
}


The simplified for loop (or, for-each loop) can be used for arrays or objects that implement java.lang.Iterable.

Note that by using generics, there's not need to down cast. But new for loop syntax doesn't down cast either. If List<String> is changed tp List<Object>, the code doesn't compile.
Share |
| Comment  | Tags
 
Easy email testing with http://www.ximailstop.com