java foreach原理

foreach语法糖

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

for(int i=0; i<list.size; i++){
//.....
}
  • 1
  • 2
  • 3

是不是很麻烦?

如果用foreach只需要这样

List<String> list = new ArrayList<String>();
for(String e : list){
//
}
  • 1
  • 2
  • 3
  • 4

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

foreach集合原理

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

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

        for(String temp : a){
           System.out.print(temp);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

反编译后的代码

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();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

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

public interface Iterator<E> {
    boolean hasNext();

    E next();

    void remove();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
public interface Collection<E> extends Iterable<E>
  • 1

foreach数组

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

同样,看反编译后的代码

 String[] arr = {"1","2"};
 for(String e : arr){
      System.out.println(e);
  }
  • 1
  • 2
  • 3
  • 4

反编译后代码

 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);
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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

posted @ 2018-04-13 09:21  nicknailo  阅读(182)  评论(0编辑  收藏  举报