首页 > 技术文章 > 增强for循环

Pireua 2021-07-14 16:42 原文

增强for循环

  • Java 5 引入了一种主要用于数组或集合的增强型for循环
  • Java增强for循环语法格式如下:
    for(声明语句 : 表达式){
        //代码句子
    }

     

  • 声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循
    环语句块,其值与此时数组元素的值相等。

  • 表达式:表达式是要访问的数组名,或者是返回值为数组的方法。
    public class ForDemo05 {
        public static void main(String[] args) {
            int[] numbers = {1,2,3,4,5};//定义了一个数组
    
            //遍历数组的元素
            for (int x :
                    numbers) {
                System.out.println(x);
            }
    
        }
    }

     

推荐阅读