Java的For-each循环

Java For-Each 数组

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.
}

Loop/Iterate an array in Java

让我们以一个字符串数组为例,您想在不使用计数器的情况下对其进行迭代。考虑一个初始化为如下的字符串数组 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 循环中声明的数据类型必须与您正在迭代的arrayList的数据类型相匹配。

For each 循环示例

这里是显示上述解释的整个类:

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);
    }
  }
}

Iterate an array in Java

预期输出

Using conventional For Loop:
Alpha
Beta
Gamma
Delta
Sigma

Using Foreach loop:
Alpha
Beta
Gamma
Delta
Sigma