Java foreach 循环原理

foreach是java的语法糖,所谓语法糖就是通过编译器或者其它手段优化了代码,给使用带来了遍历。比如,没有forach之前,我们需要这样遍历一个集合

for(int i=0; i

是不是很麻烦?

如果用foreach只需要这样

List list = new ArrayList();
for(String e : list){
//
}

是不是省事多了,不用索引值,不用判断是否越界。

foreach集合原理

但是,今天探讨的是foreach是什么,我们还是通过反编译代码来看吧。
源代码

 List a = new ArrayList();
        a.add("1");
        a.add("2");
        a.add("3");

        for(String temp : a){
           System.out.print(temp);
        }

反编译后的代码

List a = new ArrayList();
a.add("1");
 a.add("2");
 a.add("3");
 String temp;
 for(Iterator i$ = a.iterator(); i$.hasNext(); System.out.print(temp)){
    temp = (String)i$.next();
}

foreach集合相当于获取迭代器(a.iterator),通过判断是否有下一个元素(i.hasNext()∗∗),,然后移动光标(∗∗i.next());,执行操作(System.out.print(temp))

我们知道集合都实现了iterator接口

public interface Iterator {
    boolean hasNext();

    E next();

    void remove();
}
public interface Collection extends Iterable

foreach数组

好了,foreach集合的真面目,我们看懂了。因为集合实现了Iterator接口,所以遍历时走的Iterator的方法,但是foreach不只可以遍历集合,还可以遍历数组,难道数组也实现了Iterator接口?

同样,看反编译后的代码

 String[] arr = {"1","2"};
 for(String e : arr){
      System.out.println(e);
  }
反编译后代码

 String arr[] = { "1", "2"  };
  String arr$[] = arr;
  int len$ = arr$.length;
  for(int i$ = 0; i$ < len$; i$++)
  {
      String e = arr$[i$];
      System.out.println(e);
  }

可以看到foreach数组,走的是for(int i=0; i< len; i++)经典模式

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