新式for循环

新式for循环,JDK1.5之后引入的一种新的变量容器的方式

public class MyTest {
    public static void main(String[] args) {
        //新式for循环,JDK1.5之后引入的一种新的变量容器的方式  
        //在JDK1.7之后,泛型的具体类型,只要左端写上就行,右端就不需要写 =
        ArrayList<Integer> integers = new ArrayList<>();
 
        integers.add(100);
        integers.add(1002);
        integers.add(1004);
        integers.add(1005);
        integers.add(1006);
        integers.add(1007);
        integers.add(1008);
        //size()  get()方法
        for (int i = 0; i < integers.size(); i++) {
            System.out.println(integers.get(i));
        }
        System.out.println("--------------------");
        //新式for循环 (容器中元素的数据类型 元素变量名:你要遍历的容器名字)
        for(Integer ele:integers){
            System.out.println(ele);
        }

        //用的时候选哪种for循环:如果你需要在遍历的途中,用到索引作为判断条件,那就使用普通for循环
        //新式for循环你不用操心容器的长度

    }
}
发布了56 篇原创文章 · 获赞 6 · 访问量 7772

猜你喜欢

转载自blog.csdn.net/ly823260355/article/details/88877904
今日推荐