Recipe 8.2 Using "foreach" LoopsProblemYou want a convenient means of accessing all the elements of an array or collection. SolutionUse the JDK 1.5 "foreach" construction. For example: for (String s : myList) This form of for is always read as "foreach" and is referred to that way in the documentation and the compiler messages; the colon (:) is always pronounced as "in" so that the above statement is read as "foreach String s in myList." The String named s will be given each value from myList (which is presumed to be declared as an array or Collection of String references). DiscussionThe foreach construction can be used on Java arrays and on collection classes. The compiler turns it into an iteration, typically using an Iterator object where Collection classes are involved. Example 8-2 shows foreach on an array; in a slightly longer example, Example 8-3 shows foreach on a Collection. Example 8-2. ForeachArray.javapublic class ForeachArray { public static void main(String args[]) { String[] data = { "Toronto", "Stockholm" }; for (String s : data) { System.out.println(s); } } } Example 8-3. ForeachDemo.javaimport java.util.Collection; import java.util.List; import java.util.ArrayList; public class ForeachDemo { static void iterate(Collection<String> c) { for (String s: c) System.out.println(s); } public static void main(String args[]) { List<String> l = new ArrayList<String>( ); l.add("Toronto"); l.add("Stockholm"); iterate(l); } } |