📜  Java中的for-each循环

📅  最后修改于: 2022-05-13 01:55:00.452000             🧑  作者: Mango

Java中的for-each循环

先决条件: Java中的决策制定
for-each 是另一种数组遍历技术,如 Java5 中引入的 for 循环、while 循环、do-while 循环。

  • 它以关键字for开头,就像普通的 for 循环一样。
  • 不是声明和初始化循环计数器变量,而是声明一个与数组的基本类型相同类型的变量,后跟一个冒号,然后是数组名称。
  • 在循环体中,您可以使用您创建的循环变量,而不是使用索引数组元素。
  • 它通常用于遍历数组或 Collections 类(例如,ArrayList)

句法:

for (type var : array) 
{ 
    statements using var;
}

相当于:

for (int i=0; i

Java
// Java program to illustrate
// for-each loop
class For_Each    
{
    public static void main(String[] arg)
    {
        {
            int[] marks = { 125, 132, 95, 116, 110 };
             
            int highest_marks = maximum(marks);
            System.out.println("The highest score is " + highest_marks);
        }
    }
    public static int maximum(int[] numbers)
    {
        int maxSoFar = numbers[0];
         
        // for each loop
        for (int num : numbers)
        {
            if (num > maxSoFar)
            {
                maxSoFar = num;
            }
        }
    return maxSoFar;
    }
}


Java
/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
    public static void main (String[] args) {
        List list = new ArrayList<>();
        long startTime;
        long endTime;
        for (int i = 0; i < 1000000; i++) {
            list.add(i);
        }
        // Type 1
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int i : list) {
            int a = i;
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("For each loop :: " + (endTime - startTime) + " ms");
         
        // Type 2
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int j = 0; j < list.size(); j++) {
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms");
         
        // Type 3
        startTime = Calendar.getInstance().getTimeInMillis();
        int size = list.size();
        for (int j = 0; j < size; j++) {
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("By calculating collection.size() first :: " + (endTime - startTime) + " ms");
     
        // Type 4
        startTime = Calendar.getInstance().getTimeInMillis();
        for(int j = list.size()-1; j >= 0; j--) {
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using [int j = list.size(); j > size ; j--] :: " + (endTime - startTime) + " ms");
    }
}
 
// This code is contributed by Ayush Choudhary @gfg(code_ayush)


输出:

The highest score is 132

for-each 循环的局限性
决策

  1. 当您要修改数组时,for-each 循环不合适
for (int num : marks) 
{
    // only changes num, not the array element
    num = num*2; 
}

2. for-each 循环不跟踪 index 。所以我们无法使用 For-Each 循环获取数组索引

for (int num : numbers) 
{ 
    if (num == target) 
    {
        return ???;   // do not know the index of num
    }
}

3. for-each仅在单个步骤中向前迭代数组

// cannot be converted to a for-each loop
for (int i=numbers.length-1; i>0; i--) 
{
      System.out.println(numbers[i]);
}

4. for-each不能同时处理两个决策语句

// cannot be easily converted to a for-each loop 
for (int i=0; i

5. 与简单迭代相比,for-each 也有一些性能开销

Java

/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
    public static void main (String[] args) {
        List list = new ArrayList<>();
        long startTime;
        long endTime;
        for (int i = 0; i < 1000000; i++) {
            list.add(i);
        }
        // Type 1
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int i : list) {
            int a = i;
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("For each loop :: " + (endTime - startTime) + " ms");
         
        // Type 2
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int j = 0; j < list.size(); j++) {
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms");
         
        // Type 3
        startTime = Calendar.getInstance().getTimeInMillis();
        int size = list.size();
        for (int j = 0; j < size; j++) {
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("By calculating collection.size() first :: " + (endTime - startTime) + " ms");
     
        // Type 4
        startTime = Calendar.getInstance().getTimeInMillis();
        for(int j = list.size()-1; j >= 0; j--) {
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using [int j = list.size(); j > size ; j--] :: " + (endTime - startTime) + " ms");
    }
}
 
// This code is contributed by Ayush Choudhary @gfg(code_ayush)