s-day02-增强for循环遍历数组

This commit is contained in:
2026-07-30 16:50:24 +08:00
parent c9a6769f10
commit 149301c969
@@ -0,0 +1,47 @@
package com.inmind.foreach03;
/*
增强for循环遍历数组
由于部分集合没有索引,在jdk1.5 出现了一个遍历容器的增强for循环的格式,作用简化迭代器代码
foreach循环的格式:
for(数据类型 变量名 : 容器名){
循环体;
}
格式中:
数据类型:容器中存放的数据类型
变量名:就是标识符,表示容器中每个元素
容器:就是数组或集合
循环体:java语句
注意:foreach循环其实是一个语法糖,本质不变,代码简化了,这让程序员像吃了糖一样
数组的foreach循环本质是普通for循环
使用场景:
1.如果要使用索引,那就使用普通for循环
2.如果不要使用索引,那就使用增强for循环
数组名.for自动生成
*/
public class Demo04 {
public static void main(String[] args) {
//数组的遍历
int[] arr = {10, 20, 30, 40, 50};
//普通for循环遍历数组
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println("----------");
//增强for循环(foreach循环)遍历数组
int index = 0;
for(int element : arr){
System.out.println(element);
index++;
}
for (int e : arr) {
System.out.println(e);
}
}
}