增强 for 循环(也称为 for each 循环)是 JDK 5 之后出来的一个高级的 for 循环,专门用来遍历数组和集合。
语法:
for(元素的数据类型 变量: 数组 或 Collection集合){
// 写代码
}
示例:遍历数组(不要在遍历数组的时候对数组的元素进行修改)
package com.github.collection1.demo6;
/**
* @author maxiaoke.com
* @version 1.0
*/
public class Test {
public static void main(String[] args) {
// 创建数组
int[] arr = {1, 2, 3, 4, 5};
// 遍历数组
for (int i : arr) {
System.out.println("i = " + i);
}
}
}
示例:遍历集合(不要在遍历集合的时候对集合中的元素进行增加、删除、替换等操作)
package com.github.collection1.demo7;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author maxiaoke.com
* @version 1.0
*/
public class Test {
public static void main(String[] args) {
// 创建集合
Collection<Integer> collection = new ArrayList<>();
// 向集合中添加元素
collection.add(1);
collection.add(2);
collection.add(3);
collection.add(4);
// 遍历集合
for (Integer i : collection) {
System.out.println("i = " + i);
}
}
}