There are two types of enhanced for loops, which iterate through the array and implement the container for the Iterable interface. Javac uses the Visitforeachloop () method to implement the syntax sugar, the code is as follows:
/** Translate away the Foreach loop. */Public void Visitforeachloop (Jcenhancedforloop tree) { if (types.elemtype (tree.expr.type) = = null) Visititerableforeachloop (tree); else visitarrayforeachloop (tree); }
Let's start by iterating over the array.
A Statement of the form
for (T v:arrayexpr) stmt;
(where arrayexpr is a 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.
For example, the following:
Integer[] Array = {1, 2, 3, 4, 5};for (Integer i:array) {System.out.println (i);}
The following are the results of the solution of the grammatical sugars:
For (integer[] arr$ = array, len$ = arr$.length, i$ = 0; i$ < len$; ++i$) { Integer i = arr$[i$]; { System.out.println (i); }}
Take a look at the traversal of the container, as follows:
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);}
The following are the results of the solution of the grammatical sugars:
for (Java.util.Iterator i$ = List.iterator (); I$.hasnext ();) { String str = (string) i$.next (); { System.out.println (str); }}
Javac syntax sugar enhancement for loop