1.所有的Collection集合对象,都可以使用增强for进行遍历
2.数组也可以使用增强for进行遍历
格式: for(Collection集合对象/数组对象 存储元素的类型 变量名称 : Collection集合对象/数组对象){
...
}
注意: 1.变量名称不是用来存储数组的索引值的,而是用来存储数组中的每个元素的
3.增强for遍历数组时,请不要对数组元素进行增删改的操作,否则出现问题,自己解决
4.增强for遍历数组快捷键:
数组名.for
### 增强for遍历数组
数组定义格式: 数据类型[] 数组名称 = new 数据类型[长度];
int[] arr = new int[3];
格式: for(数组存储元素的类型 变量名称 : 数组) {
...
}
public class Demo03NBForArray {
public static void main(String[] args) {
int[] arr = {10,20,30,50};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
for(int num : arr){
System.out.println(num);
}
}
}
增强for遍历集合
集合定义格式: ArrayList<数据类型> 集合名称 = new ArrayList<数据类型>();
ArrayList<String> list = new ArrayList<>();
格式: for(集合存储元素的类型 变量名称 : 集合) {
... }
public class Demo04NBForCollection {
public static void main(String[] args) {
Collection<String> coll = new ArrayList<>();
coll.add("hello");
coll.add("world");
coll.add("java");
Iterator<String> it = coll.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
for(String s : coll){
System.out.println(s);
}
}
}