Javac syntax sugar enhancement for loop

Source: Internet
Author: User
Tags iterable

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

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.