foreach
数组遍历
public class ForEachTest {
public static void main(String[] args) {
// int类型数组
int[] arr = {1,2,3,4,5,6};
// 遍历数组
// 普通for循环
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// 增强for循环(foreach)
/* 语法:
for (元素类型 变量名 : 数组或集合) {
System.out.println(变量名);
}*/
// 缺点:没有下标,在需要使用下标的循环中不建议使用
for (int i : arr) {
System.out.println(i);
}
}
}
集合遍历
public class ForEachTest1 {
public static void main(String[] args) {
// 创建List集合
List<String> strList = new ArrayList<>();
// 添加元素
strList.add("asd");