传统for循环遍历数组:
public class for01{
public static void main(String[] args){
//定义一个长度为5的数组
int nums = new int[5];
//传统的遍历数组元素的for循环结构
//此处的计数器为数组元素的索引,一般初始化为0
//进入循环体的表达式一般写为:索引小于被遍历数组的长度
//每次循环体执行结束后会对索引进行加1操作
for(int index = 0; index < nums.length; index++){
//通过数组的索引来为相应的数组元素赋值
nums[index] = index + 1;
}
for(int index = 0; index < nums.length; index++){
System.out.print(nums[index]);
}
}
}
运行结果:1 2 3 4 5
增强for循环遍历数组:
public class foreach01{
public static void main(String[] args){
//定义一个长度为5的数组
int nums = new int[5];
for(int index = 0; index < nums.length; index++){
//通过数组的索引来为相应的数组元素赋值
nums[index] = index + 1;
}
// for(type v : array){
// 循环体
// }
// type为数组元素的类型
// v是一个变量,保存着当前被处理的那个数组元素
// array是被遍历的数组
for(int num : nums){
System.out.print(num);
}
}
}
运行结果:1 2 3 4 5
【注】Java 5 引用的增强for循环(foreach),是用于遍历数组或集合中数据元素的循环结构;
此循环结构会从数组或集合的第一个元素开始,处理每一个元素,直到最后一个元素被处理完毕才会结束循环;
比起传统的遍历方式,此结构的代码更加简单,遍历过程不会出现元素索引越界的情况。