增强for循环(foreach循环)
增强for循环:底层使用的也是迭代器,只是使用for循环的格式,简化了迭代器的书写;但使用foreach循环迭代数组元素时,并不能改变数组元素的值,因此不要对foreach的循环变量进行赋值。
作用:用来遍历集合和数组。使遍历变得简洁。
快捷键:arr.for-->for(int i:arr){}
格式: for(集合/数组的数据类型 变量名:集合名/数组名){ sout(变量名); }
public class Demo {
public static void main(String[] args) {
int[] arr = {5,4,3,2,1};
//for(集合/数组的数据类型 变量名:集合名/数组名)
for(int i:arr){//快捷键:arr.for
System.out.println(i);//变量名
}
}
}
输出结果:
5
4
3
2
1
public class DemoIterator {
public static void main(String[] args) {
Collection<String> coll = new ArrayList<>();
coll.add("hello");
coll.add("world");
coll.add("java");
for (String s:coll){
System.out.println(s);
}
}
}
输出结果:
hello
world
java