Java for-each(增强)循环 (Java for-each (Enhanced for) loop)
for loop is used to execute a block of statements, multiple times if the user knows exactly how many iterations are needed or required.
for循环用于执行语句块,如果用户确切知道需要或需要多少次迭代,则使用多次。
Java supports an enhanced version of for loop which is also called for-each loop or enhanced for loop. This loop works on collections (iterable). It iterates over each element of the sequence on by one and executes them.
Java支持for循环的增强版本,也称为for-each循环或增强的for循环 。 此循环适用于集合(可迭代)。 依次迭代序列的每个元素并执行它们。
Note: Unlike for loop, you cannot alter the content of the sequence inside the for-each loop.
注意:与for循环不同,您不能在for-each循环内更改序列的内容。
Syntax of for-each (enhanced for) loop:
for-each(增强的)循环的语法:
for (data_type variable : collection){
//body of the loop;
}
It stores each item of the collection in variable and then executes it.
它将集合的每个项目存储在变量中,然后执行它。
Note: data_type should be the same as the data_type of the collection.
注意: data_type应该与集合的data_type相同。
Java代码演示for-each(增强的)循环示例 (Java code to demonstrate example of for-each (enhanced for) loop)
// java program to demonstrate example of
// for-each (enhanced for) loop
//file name: includehelp.java
public class includehelp {
public static void main(String[] args) {
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("Demonstration of for-each loop");
// for-each loop iterating over array
// with the variable x
// if you change the value of x inside
// the body of the loop then original
// value of the array will remain unaffected
for (int i : array)
System.out.println(i);
}
}
Output
输出量
Demonstration of for-each loop
1
2
3
4
5
6
7
8
9
翻译自: https://www.includehelp.com/java/for-each-enhanced-for-loop.aspx