foreach概述
增強for循環:底層使用的是送代器,使用for循環的格式,簡化了送代器的書寫,foreach是JDK1.5之后出現的新特性
使用增強for循環
遍歷集合
/**
* 遍歷集合
* @param arrayList 集合
*/
public static void demoCollection(ArrayList<String> arrayList) {
for (String string: arrayList) {
System.out.println(string);
}
}
public class DemoForEach {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("集合1號");
arrayList.add("集合2號");
arrayList.add("集合3號");
arrayList.add("集合4號");
arrayList.add("集合5號");
// 遍歷集合
demoCollection(arrayList);
}
}
輸出結果:
集合1號
集合2號
集合3號
集合4號
集合5號
遍歷數組
/**
* 遍歷數組
* @param strings 數組
*/
public static void demoArray(String[] strings) {
for (String string: strings) {
System.out.println(string);
}
}
public class DemoForEach {
public static void main(String[] args) {
String[] strings = {"數組1號", "數組2號", "數組3號", "數組4號", "數組5號"};
// 遍歷數組
demoArray(strings);
}
}
輸出結果:
數組1號
數組2號
數組3號
數組4號
數組5號
