集合-新特性foreach循环遍历集合或项目

1.增强for循环对集合的遍历

点击查看代码
 @Test
    //集合遍历
    public void test3(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        //for(集合中元素的类型 局部变量 : 集合对象)
        //按顺序每次取集合中的元素,然后将其赋值给obj,然后输出
        for(Object obj : coll){
            System.out.println(obj);
        }
    }

运行结果图

2.增强for循环对数组的遍历

点击查看代码
    @Test
    //数组遍历
    public void test4(){
        int[] arr = new int[]{7,8,3,4};
        //for(数组中元素的类型 局部变量 : 数组对象)
        //按顺序每次取数组中的元素,然后将其赋值给i,然后输出
        for(int i : arr){
            System.out.println(i);
        }
    }
运行结果图

posted @ 2022-07-12 09:33  剑断青丝ii  阅读(42)  评论(0编辑  收藏  举报