CodeGym/Java 博客/China/Java 中的 for-each 循环
作者
Artem Divertitto
Senior Android Developer at United Tech

Java 中的 for-each 循环

已在 China 群组中发布
个会员

什么是 for-each 循环?

for-each 是一种 for 循 环,当你需要处理数组或集合的所有元素时使用。也就是说,这个循环中实际上并没有使用 for-each 这个短语。语法如下:
for (type itVar : array)
{
    // Operations
}
其中,type 是迭代器变量(该变量与数字中的元素数据类型匹配!),itVar 是其名称,array 是数组(还允许使用其他数据结构,例如,某种集合,诸如 ArrayList),即执行循环的对象。如你所见,这个构造没有使用计数器:迭代器变量只是简单地遍历数组或集合的元素。当执行这样的循环时,迭代器变量按顺序分配数组或集合的每个元素的值,然后执行指定的语句块(或语句)。 注意: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 循环。

CodeGym 课程中的循环

在 CodeGym 上,你开始在 Java 语法目标的第 4 级上使用数组。该级别的几个课程,以及不同级别的许多任务,都是专门针对循环的,目的是强化你使用循环的技能。基本上,你没有办法多开循环,因为循环是编程中最重要的构造之一。 Java 中的 for-each 循环 - 1

有关 for-each 和其他循环的更多信息

  1. while 语句。这篇文章会介绍最简单的循环:while 循环,而 CodeGym 正是使用该循环向学生讲解循环的。
  2. 停止编写循环!在 Java 8 中处理集合的前 10 个最佳实践。这篇文章将帮助学了半截 CodeGym 课程的学生学习许多关于使用集合的有趣事情。
评论
  • 受欢迎
你必须先登录才能发表评论
此页面还没有任何评论