加强的for循环有两种,遍历数组和实现了Iterable接口的容器。javac通过visitForeachLoop()方法来实现解语法糖,代码如下:
/** Translate away the foreach loop. */ public void visitForeachLoop(JCEnhancedForLoop tree) { if (types.elemtype(tree.expr.type) == null) visitIterableForeachLoop(tree); else visitArrayForeachLoop(tree); }
首先来看遍历数组。
A statement of the form
for ( T v : arrayexpr ) stmt;
(where arrayexpr is of an array type) gets translated to
for ( { arraytype #arr = arrayexpr; int #len = array.length; int #i = 0; }; #i < #len; i$++ ) { T v = arr$[#i]; stmt; }
where #arr, #len, and #i are freshly named synthetic local variables.
举个例子,如下:
Integer[] array = { 1, 2, 3, 4, 5 }; for (Integer i : array) { System.out.println(i); }
解语法糖后的结果如下:
for (Integer[] arr$ = array, len$ = arr$.length, i$ = 0; i$ < len$; ++i$) { Integer i = arr$[i$]; { System.out.println(i); } }
来看看对容器的遍历,如下:
A statement of the form
for ( T v : coll ) stmt ;
(where coll implements Iterable<? extends T>) gets translated to
for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) { T v = (T) #i.next(); stmt; }
where #i is a freshly named synthetic local variable.
List<String> list = new ArrayList<String>(); for(String str:list){ System.out.println(str); }
解语法糖后的结果如下:
for (java.util.Iterator i$ = list.iterator(); i$.hasNext(); ) { String str = (String)i$.next(); { System.out.println(str); } }