1. Overview
1.概述
In this tutorial, we’ll discuss the for-each loop in Java along with its syntax, working, and code examples. Finally, we’ll understand its benefits and drawbacks.
在本教程中,我们将讨论Java中的for-each循环,以及它的语法、工作原理和代码示例。最后,我们将了解它的好处和坏处。
2. Simple for Loop
2.简单的for循环
The simple for loop in Java essentially has three parts – initialization, boolean condition & step:
Java中简单的for loop本质上有三个部分–初始化、boolean条件& 步骤:
for (initialization; boolean-condition; step) {
statement;
}
It starts with the initialization of a loop variable, followed by a boolean expression. If the condition is true, it executes the statement(s) in the loop and increments/decrements the loop variable. Otherwise, it terminates the loop.
它以一个循环变量的初始化开始,然后是一个boolean表达式。如果条件是真,它将执行循环中的语句,并增加/减少循环变量。否则,它将终止循环。
This pattern makes it slightly complex and difficult to read. Moreover, if we do not write the condition properly, there’s always a chance to get into an infinite loop.
这种模式使得它略显复杂,难以阅读。此外,如果我们没有正确地写出条件,总是有机会进入无限循环。
3. for-each Loop
3.for-each 循环
The for-each loop was introduced in Java 5. We also call it an enhanced for loop.
for-each循环是在Java 5中引入的。我们也称它为增强型for循环。。
It’s an alternate traversing technique specifically introduced to traverse arrays or collections. Noticeably, it also uses the for a keyword. However, instead of using a loop counter variable, we assign a variable of the same type as that of an array or a collection.
这是一种替代性的遍历技术,专门用于遍历数组或集合。值得注意的是,它也使用了for a关键字。但是,我们没有使用循环计数器变量,而是分配了一个与数组或集合类型相同的变量。
The name for-each signifies that each element of an array or a collection is traversed, one after another.
for-each这个名字表示数组或集合中的每个元素都被逐一遍历。
3.1. Syntax
3.1 语法
The for-each loop consists of the declaration of a loop variable followed by a colon (:), which is followed by the name of an array or collection:
for-each循环由一个循环变量的声明组成,后面是冒号(:),冒号后面是一个数组或集合的名称。
for (data_type var_name : array | collection) {
// code
}
3.2. Working
3.2.工作
For each iteration, the for-each loop takes each element of the collection and stores it in a loop variable. Thus, it executes the code written in the body of the loop for each element of the array or collection.
对于每一次迭代,for-each 循环会获取集合中的每个元素,并将其存储在一个循环变量中。因此,它为数组或集合的每个元素执行写在循环主体中的代码。
Most importantly, the traversal happens until the last element of the array or collection.
最重要的是,这种遍历一直发生到数组或集合的最后一个元素。
3.3. Examples
3.3.实例
Let’s see an example of traversing an array with the for-each loop:
让我们看一个用for-each循环遍历数组的例子。
int numbers[] = { 1, 2, 3, 4, 5 };
for (int number : numbers) {
System.out.print(number + " ");
}
Here, the for-each loop traverses over each element of the array numbers one by one until the end. Therefore, there’s no need to access the array elements using indexing.
在这里,for-each循环逐一遍历数组numbers中的每个元素,直到结束。因此,不需要使用索引来访问数组元素。
Now, let us see some examples of traversing various collections with the for-each loop.
现在,让我们看看用for-each循环遍历各种集合的一些例子。
Let’s start with a List:
让我们从一个列表开始。
String[] wordsArray = { "Java ", "is ", "great!" };
List<String> wordsList = Arrays.asList(wordsArray);
for (String word : wordsList) {
System.out.print(word + " ");
}
Similarly, we can traverse through all the elements of a Set:
同样地,我们可以遍历Set的所有元素。
Set<String> wordsSet = new HashSet();
wordsSet.addAll(wordsList);
for (String word : wordsSet) {
System.out.print(word + " ");
}
Additionally, we can also use the for-each loop to traverse through a Map<K, V> as well:
此外,我们还可以使用for-each循环来遍历Map<K, V> 。
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "is");
map.put(3, "great!");
for (Entry<Integer, String> entry : map.entrySet()) {
System.out.println(
"number: " + entry.getKey() +
" - " +
"Word: " + entry.getValue());
}
In the same way, we can use a for-each loop to iterate through various other data structures in Java.
同样,我们可以使用for-each循环来迭代Java中的其他各种数据结构。
However, if the array or collection is null, it throws a NullPointerException:
然而,如果数组或集合是null,它会抛出一个NullPointerException:。
int[] numbers = null;
for (int number : numbers) {
System.out.print(number + " ");
}
The above code throws a NullPointerException:
上述代码抛出一个NullPointerException。
Exception in thread "main" java.lang.NullPointerException
at com.baeldung.core.controlstructures.loops.ForEachLoop.traverseArray(ForEachLoop.java:63)
..
Hence, we must check if the array or collection is null before passing it to the for-each loop.
因此,我们必须在将数组或集合传递给for-each循环之前检查其是否为null。
The for-each loop doesn’t execute at all if the array or collection is empty.
如果数组或集合是空的,for-each循环就根本不执行。
3.4. Pros and Cons
3.4.优点和缺点
The for-each loop is one of the important features introduced in Java 5. However, it also has its own benefits and drawbacks.
for-each循环是Java 5中引入的重要功能之一。然而,它也有自己的好处和缺点。
The benefits of the for-each loop are:
for-each循环的好处是。
- It helps us avoid programming errors.
- It makes the code precise and readable.
- It’s easier to implement.
- It avoids the chance of an infinite loop.
Because of these benefits, we prefer the for-each loop over the for loop, especially while working with arrays or collections.
由于这些好处,我们更喜欢for-each循环而不是for循环,尤其是在处理数组或集合时。
The drawbacks of the for-each loop are:
for-each循环的缺点是。
- We can’t jump over an element as it traverses through each element.
- Traversing in reverse order is not possible.
- We can’t modify the array if we’re using a for-each loop.
- It’s not possible to keep track of the index.
- It has some performance overhead over the for a loop.
4. Conclusion
4.总结
In this article, we explored the for-each loop in Java along with its syntax, working, and examples. Finally, we saw its benefits and drawbacks.
在这篇文章中,我们探讨了Java中的for-each循环,以及它的语法、工作和例子。最后,我们看到了它的好处和坏处。
As always, the code for these examples is available over on GitHub.
像往常一样,这些例子的代码可以在GitHub上找到over。