CodeGym /Java Blog /Toto sisi /Java 中的 for-each 循環
John Squirrels
等級 41
San Francisco

Java 中的 for-each 循環

在 Toto sisi 群組發布

什麼是 for-each 循環?

for -each是一種for循環,在需要處理數組或集合的所有元素時使用。也就是說,for-each這個短語實際上並沒有用在這個循環中。它的語法如下:

for (type itVar : array) 
{ 
    // Operations
}
其中type是迭代器變量的類型(它匹配數組中元素的數據類型!),itVar是它的名稱,array是一個數組(也允許使用其他數據結構,例如某種集合,如ArrayList ),即執行循環的對象。如您所見,此構造不使用計數器:迭代器變量只是迭代數組或集合的元素。當執行這樣的循環時,迭代器變量被順序賦值給數組或集合的每個元素,之後執行指定的語句塊(或語句)。

除了 for-each 循環之外,Java 還有一個 forEach() 方法。您可以在標題為“停止編寫循環!”的文章中閱讀相關內容。在 Java 8 中使用集合的十大最佳實踐

筆記:for -each循環可以應用於數組和任何實現java.lang.Iterable接口的類。下面的for循環等價於上面的代碼:

for (int i=0; i < array.length; i++) 
{ 
    
    // Statements 
}

for-each 循環示例

我們創建了一系列學生分數。然後我們使用for-each循環打印出所有的估計值,計算平均分,並找到最高分。

public class ForEachTest {
    
// A method that prints all scores     
public static void printAllScores(int[] scores) {
        System.out.print("|");
        for (int num : scores) {

            System.out.print(num + "|");
        }
        System.out.println();
    }

// A method that displays the average score 
    
public static double getAverageScore(int[] numbers) {
        int totalScore = 0;

        for (int num : numbers) {
            totalScore = num + totalScore;
        }
        return ((double) totalScore / numbers.length);

    }
// A method that determines the best (maximum) score 
    public static int getBestScore(int[] numbers) {
        int maxScore = numbers[0];

        for (int num : numbers) {
            if (num > maxScore) {
                maxScore = num;
            }
        }
        return maxScore;
    }

public static void main(String[] args) {
      
// Array of scores 
int[] scores = {5, 10, 7, 8, 9, 9, 10, 12};

        
  int bestScore = getBestScore(scores);
        System.out.print("All the scores: ");
        printAllScores(scores);
        System.out.println("The highest score is " + bestScore);
        System.out.println("The average score is " + getAverageScore(scores));
    }

}
程序輸出:

All the scores: |5|10|7|8|9|9|10|12|
The highest score is 12
The average score is 8.75
現在,讓我們看看如果我們使用普通的for循環, 打印所有分數的方法會是什麼樣子:

public static void printAllScores(int[] scores) {
        System.out.print("|");
        for (int i = 0; i < scores.length; i++) {

            System.out.print(scores[i] + "|");
        }
        System.out.println();
    }
如果我們從main方法調用這個方法,那麼我們會得到這個結果:

All the scores: |5|10|7|8|9|9|10|12|

帶有集合的 for-each 循環示例

我們創建一個名稱集合併在屏幕上顯示所有名稱。

List<String> names = new ArrayList<>();
        names.add("Snoopy");
        names.add("Charlie");
        names.add("Linus");
        names.add("Shroeder");
        names.add("Woodstock");

        for(String name : names){
            System.out.println(name);
        }

for-each 循環的局限性

for -each循環的緊湊形式被認為比for循環更易於閱讀,並且盡可能使用for-each循環被認為是最佳實踐。但是,與普通的for循環相比, for-each循環的通用性較低。以下是一些簡單的情況,其中for-each循環要么根本不起作用,要么會起作用,但有困難。
  1. 如果你想從頭到尾運行一個循環。也就是說,沒有直接類似於以下代碼的for-each循環:

    
    for (int i= array.length-1; i>0; i--) 
    {
          System.out.println(array[i]);
    }
    
  2. 如果您想對數組進行更改,則 For-each 不適合。例如,您不能在不更改數組元素位置的情況下對數組進行排序。此外,在下面的代碼中,只有迭代器變量會發生變化,數組的元素不會發生變化:

    
    for (int itVar : array) 
    {
        itVar = itVar++; 
    }
    
  3. 如果你正在尋找數組中的一個元素並且你需要返回(或傳遞)你正在尋找的元素的索引,那麼最好使用普通的 for循環

有關 for-each 循環的有用視頻

CodeGym 課程中的循環

在 CodeGym 上,我們在Java 語法任務的第 4 級開始練習使用循環。該級別的一些課程以及不同級別的許多任務都致力於循環,以加強您使用它們的技能。基本上,您無法逃避它們——循環是編程中最重要的結構之一。

有關 for-each 和其他循環的更多信息

  1. while 語句。這篇文章講的是最簡單的一種循環:while循環,CodeGym用它來給同學們介紹循環。
  2. 停止寫循環!在 Java 8 中使用集合的十大最佳實踐。本文將幫助至少完成課程一半的 CodeGym 學生學習許多關於使用集合的有趣知識。
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION