增強的for語句
增強的for語句形式如下:
for(Type loop-variable:set - expression)
statement
其中set - expression必須為確定的對象,這個對象是我們想要迭代的數值的集合。loop-variable是一個局部變量,它的類型Type必須適合于數值集合set - expression的內容,每次進行循環時,loop-variable都會從set - expression取出下一個值,然后執行statement,直到取完集合中的數據。
set - expression必須是數組或者實現了java.lang.Iterable接口的對象
它的好處是不用手工維護數組下標,也不必檢查數組的長度。
它的缺點是只能在單獨的一個數組上向前循環,并且只能查看數組的元素
下面是例子:
import java.util.Vector;
public class ForEx {
public static void main(String[] args) {
Vector<String> v=new Vector<String>();
v.add("Hello");
v.add("Hi");
v.add("Good Moning");
for (String string : v) {
System.out.println(string);
}
}
}
輸出結果:
Hello
Hi
Good Moning
如果這個“增強的for語句”和“引元數量可變的方法”聯合起來一起用的話會有不錯的效果:
public class Test {
public static void main(String[] args) {
Test t=new Test();
t.test("hello,","hi");
t.test("good morning");
t.test("good afternoon,","good evening,","good night");
}
public void test(String... body){
//String...代表String的數組,長度由傳進來時的數組長度決定
for (String string : body) {
System.out.println(string);
}
}
}
輸出如下:
hello,
hi
good morning
good afternoon,
good evening,
good night