foreach实现原理

1.数组

  数组使用foreach循环直接遍历数组循环,代码:

    public static void main(String[] args) {
        String[] strs = new String[1];
        for (String str : strs) {
            System.out.println(str);
        }
    }

  使用javap编译class文件,第一次编译遇到报错:

  

  使用命令javac -enconding UTF-8 ForEachTest.java改变编码格式后,在使用javap -c xxx.class查看反编译代码:

  

2.实现了Iterable的类

  实现Iterable接口的类,foreach循环使用的是迭代器iterator遍历数组,代码:

    public static void main(String[] args) {
        Collection<String> collections = new ArrayList<>();
        for (String str : collections) {
            System.out.println(str);
        }
    }

  使用javap反编译结果:

  

 

posted @ 2017-06-05 14:34  莫莫莫  阅读(245)  评论(0)    收藏  举报