Anti-compilation See Java For-each loop

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.