Java Foreach语法

Motivation: Java SE5引入了一种新的更加简洁的for语法用于数组和容器。

Definition:表示不必创建int变量去对由访问项构成的序列进行计数,foreach将自动产生第一项。

 

Sample:


//: control/ForEachFloat.java package control; /* Added by Eclipse.py */ import java.util.*; public class ForEachFloat { public static void main(String[] args) { Random rand = new Random(47); float f[] = new float[10]; for(int i = 0; i < 10; i++) f[i] = rand.nextFloat(); for(float x : f) System.out.println(x); } } /* Output: 0.72711575 0.39982635 0.5309454 0.0534122 0.16020656 0.57799757 0.18847865 0.4170137 0.51660204 0.73734957 *///:~ //: control/ForEachInt.java package control; /* Added by Eclipse.py */ import static net.mindview.util.Range.*; import static net.mindview.util.Print.*; public class ForEachInt { public static void main(String[] args) { for(int i : range(10)) // 0..9 printnb(i + " "); print(); for(int i : range(5, 10)) // 5..9 printnb(i + " "); print(); for(int i : range(5, 20, 3)) // 5..20 step 3 printnb(i + " "); print(); } } /* Output: 0 1 2 3 4 5 6 7 8 9 5 6 7 8 9 5 8 11 14 17 *///:~  //: control/ForEachString.java package control; /* Added by Eclipse.py */ public class ForEachString { public static void main(String[] args) { for(char c : "An African Swallow".toCharArray() ) System.out.print(c + " "); } } /* Output: A n A f r i c a n S w a l l o w *///:~ 

你可能感兴趣的:(Java Foreach语法)