Java foreach原理

public class ForEachDemoTest {

    public static void main(String[] args) {


    }
    //数组形式的foreach底层字节码原理同for相同
    public void test(){
        int[] arr = new int[]{1,2,3,4,5,65,6};
        for(int i :arr){
            System.out.println(i);
        }
    }

    /**
     * 39 aload_1
     40 arraylength
     41 if_icmpge 59 (+18)
     44 getstatic #2 
     47 aload_1
     48 iload_2
     49 iaload
     50 invokevirtual #3 
     53 iinc 2 by 1
     56 goto 38 (-18)
     */
    public void test2(){
        int[] arr = new int[]{1,2,3,4,5,65,6};
        for(int i = 0;i count 1
     59 astore_2
     60 aload_2
     61 invokeinterface #13  count 1
     66 ifeq 86 (+20)
     69 aload_2
     70 invokeinterface #14  count 1
     */
    public void forEachList(){
        List list = new ArrayList();
        list.add("name-1");
        list.add("name-2");
        list.add("name-3");
        list.add("name-4");
        list.add("name-5");
        for(Object obj:list ){
            System.out.println(obj);
        }
    }
}

你可能感兴趣的:(Java foreach原理)