Java中的for-each(增强的for循环)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值