foreach循环

来源:互联网 发布:java中接口怎么写 编辑:程序博客网 时间:2024/06/05 09:50
没有forach之前,我们需要这样遍历一个集合
for(int i=0; i<list.size; i++){//.....}

如果用foreach只需要这样
List<String> list = new ArrayList<String>();for(String e : list){//}

是不是省事多了,不用索引值,不用判断是否越界。
foreach集合原理
源代码
 List<String> a = new ArrayList<String>();        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<E> {    boolean hasNext();    E next();    void remove();}public interface Collection<E> extends Iterable<E>
foreach数组
因为集合实现了Iterator接口,所以遍历时走的Iterator的方法,但是foreach不只可以遍历集合,还可以遍历数组?
同样,看反编译后的代码
 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++)经典模式。