The For-each loop introduced in the Java 1.5 release. (from "effective Java" Chinese version of the second edition of the 46th article )
Example of the For-each loop for the following array list:
1 Public classForEach {2 Public Static voidMain (string[] args) {3java.util.arraylist<string> list =NewJava.util.arraylist<string>();4 for(String s:list) {5 //TODO6 }7 }//main8}
In the jdk1.8.0_151 environment, use the Javac tool to compile the code above, get the Foreach.class bytecode file, and then use JAVAP to decompile the bytecode file, as shown in:
Note that the Java.util.Iterator class appears for the anti-compilation result, and its hasnext and next methods appear.
See here, probably also understand, For-each loop in essence is actually the use of the iterator pattern.
To put it simply, the code at the beginning of the article is actually like this:
1 Public classForEach {2 Public Static voidMain (string[] args) {3java.util.arraylist<string> list =NewJava.util.arraylist<string>();4Java.util.iterator<string> iter =list.iterator ();5 while(Iter.hasnext ()) {6 Iter.next ();7 }8}//Main9}
Two comparisons, For-each more concise, this is the advantage of For-each.
Therefore, it can be said that the For-each loop is a syntactic sugar in Java.
"Summary": The For-each loop is Java syntax sugar, which is essentially the use of an iterator pattern.
Anti-compilation See Java For-each loop