44、增强for循环

增强for循环(foreach循环)

增强for循环:底层使用的也是迭代器,只是使用for循环的格式,简化了迭代器的书写;但使用foreach循环迭代数组元素时,并不能改变数组元素的值,因此不要对foreach的循环变量进行赋值。

作用:用来遍历集合和数组。使遍历变得简洁。
快捷键arr.for-->for(int i:arr){}

格式:
	for(集合/数组的数据类型 变量名:集合名/数组名){
        sout(变量名);
    }
public class Demo {
   public static void main(String[] args) {
       int[] arr = {5,4,3,2,1};
       
       //for(集合/数组的数据类型 变量名:集合名/数组名)
       for(int i:arr){//快捷键:arr.for
           System.out.println(i);//变量名
       }
   }
}

输出结果
5
4
3
2
1


public class DemoIterator {
    public static void main(String[] args) {
        Collection<String> coll = new ArrayList<>();
        coll.add("hello");
        coll.add("world");
        coll.add("java");

        for (String s:coll){
            System.out.println(s);
        }
    }
}

输出结果
hello
world
java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值