For-Each 示例:增强 for 循环以迭代 Java 数组
For-Each 循环是用于遍历数组的另一种形式的 for 循环。 for-each 循环显着减少了代码,并且没有使用索引或循环中的计数器。
语法:
For(<DataType of array/List><Temp variable name> : <Array/List to be iterated>){
System.out.println();
//Any other operation can be done with this temp variable.
}
让我们以一个字符串数组为例,您希望在不使用任何计数器的情况下对其进行迭代。
考虑一个 String 数组 arrData 初始化如下:
String[] arrData = {"Alpha", "Beta", "Gamma", "Delta", "Sigma"};
尽管您可能知道诸如查找数组大小然后使用传统的 for 循环(计数器、条件和增量)遍历数组的每个元素之类的方法,但我们需要找到一种更优化的方法,它不会使用任何此类计数器.
这是“for”循环的常规方法:
for(int i = 0; i< arrData.length; i++){
System.out.println(arrData[i]);
}
可以看到计数器的使用情况,然后将其作为数组的索引。
Java 提供了一种使用“for”循环的方法,该循环将遍历数组的每个元素。
这是我们之前声明的数组的代码-
for (String strTemp : arrData){
System.out.println(strTemp);
}
您可以看到循环之间的差异。 代码 减少了 显著地。另外,没有使用索引 或者更确切地说是 循环中的计数器 .
确保数据类型 在 foreach 循环中声明必须匹配 您正在迭代的数组/列表的数据类型 .
这里我们有显示上述解释的整个类-
class UsingForEach {
public static void main(String[] args) {
String[] arrData = {"Alpha", "Beta", "Gamma", "Delta", "Sigma"};
//The conventional approach of using the for loop
System.out.println("Using conventional For Loop:");
for(int i=0; i< arrData.length; i++){
System.out.println(arrData[i]);
}
System.out.println("\nUsing Foreach loop:");
//The optimized method of using the for loop - also called the foreach loop
for (String strTemp : arrData){
System.out.println(strTemp);
}
}
}
输出:
Using conventional For Loop: Alpha Beta Gamma Delta Sigma Using Foreach loop: Alpha Beta Gamma Delta Sigma
java