Java:foreach Implementation principle

Source: Internet
Author: User
Tags iterable

The first part: For-eachLooppurpose

The basic for loop is extended in Java 5 to make iteration through arrays and other collections more convenient. This newer for statement are called the enhanced for or For-each (because it's called this in O Ther programming languages). I ' ve also heard it called the for-in loop.

Use it on preference to the standard for loop if applicable (see last section below) because it's much more Reada ble.

Series of Values. The For-each loop is used to access each successive value in a collection of values.

Arrays and Collections. It ' s commonly used to iterate over an array or a collections class (eg, ArrayList).

iterable<e>. It can also iterate over anything that implements the iterable<e> interface (must define iterator() method). Many of the collections classes (eg, ArrayList ) implement iterable<e>, which makes theFor-each loop ve Ry useful. You can also implement iterable<e> for your own data structures.

General Form

The For-each and equivalent for statements has these forms. The both basic equivalent forms are given, depending one whether it's an array or a iterable that's being Trave Rsed. In both cases a extra variable is required, a index for the array and a iterator for the collection.

Here we just need to know the following facts are good:

    1. Inside the For-each syntax, the collection is implemented with nested iteratoration, and the array is implemented with subscript traversal.
    2. Compilers in Java 5 and above hide internal implementations based on iteration and subscript traversal. (Note that this is the Java compiler or the Java language that hides its implementation, rather than a piece of Java code that hides its implementation, that is, we cannot find a hidden implementation here in any Java code of the JDK.) The implementation here is hidden in the Java compiler, and we may only be able to look at the bytecode compiled by a For-each Java code as described in this post, and speculate on how it was implemented.

The following comparisons of "For-each" and "Iteration/index implementations of their equivalents" are clear and concise.

For-each Loop equivalent for loop
for (type vararr) {    body-of-loop}
I arr I+ +) {     type vararr[i];    Body-of-loop}
for (type varcoll) {    body-of-loop}
For (iterator<typeiterColliterhasnext ();) {    type variter. Next ();    Body-of-loop}
Example-adding all elements of an array

Here are a loop written as both a For-each loop and a basic for loop.

double[] ar = {1.2, 3.0, 0.8};int sum = 0;for (double d:ar) {  //D gets successively each value in AR.    sum + = D;}

And here's the same loop using the basic for. It requires an extra iteration variable.

double[] ar = {1.2, 3.0, 0.8};int sum = 0;for (int i = 0; i < ar.length; i++) {  //I indexes each element successiv Ely.    Sum + = Ar[i];}
Where the For-eachIs appropriate must pay attention to For-each is not omnipotent, the following occasions are not suitable for use For-each

Altho the enhanced for loop can make code much clearer, it can ' t is used in some common situations.

Cannot assign to collection or elements in an array when using For-each

    • Only access. Elements can not is assigned to, eg, not to increment each element in a collection.

You can only traverse one collection or array at a time, and you cannot traverse an extra collection or array at the same time

    • Only single structure. It's not possible to traverse and structures at once, eg, to compare, and arrays.

During traversal, only one element in the collection or array is visible, that is, only the element that is currently traversed is visible, and the previous or last element is invisible.

    • Only a single element. Use with only a single element access, eg, not to compare successive elements.

Only forward traversal, not reverse traversal (in contrast, C + + STL also has reverse_iterator, Rbegin (), Rend () and other things, you can reverse traversal)

    • Only forward. It's possible to iterate only forward by single steps.

You cannot use For-each if you want to be compatible with Java versions prior to Java 5

      • At least Java 5. Don ' t use it if you need compatibility with versions before Java 5.

This article from: http://blog.csdn.net/yasi_xi/article/details/25482173#t1

Part II:

Let's take a look at this piece of code:

public static void Main (string[] args) {    list<string> List = new arraylist<string> ();    List.add ("111");    List.add ("222");        for (String str:list)    {        System.out.println (str);}    }

Using a Foreach loop to traverse the list, the result is not said, all know. Take a look at how Java handles this foreach loop, Javap decompile:

D:\myeclipse\testarticle\bin\test29>javap-verbose Testmain.class

There is a lot of anti-compilation content, such as class information, symbolic reference, byte code information, to intercept a piece of information:

1 public   static void Main (java.lang.string[]); 2     flags:acc_public, acc_static 3     code:4       stack=2, Locals=4, args_size=1 5          0:new           #16                 //class Java/util/arraylist 6          3:dup 7          4:invokespecial #18                 Method java/util/arraylist. " <in 8 it> ":() V 9          7:astore_110          8:aload_111          9:ldc           #19                 //String 11112         11: Invokeinterface #21,  2           //Interfacemethod java/util/list.13 add: (ljava/lang/object;) Z14         16:POP15         17:aload_116         18:ldc           #27                 //String 22217         20:invokeinterface #21,  2           // Interfacemethod java/util/list.18 add: (ljava/lang/object;) Z19         25:pop20         26:aload_121         27: Invokeinterface #29,  1           //Interfacemethod java/util/list.22 iterator: () Ljava/util/iterator;

It doesn't matter, new, DUP, invokespecial These are the instructions defined in the bytecode instruction table, and the virtual opportunity executes the specified C + + code according to these instructions to complete the function of each instruction. Key See 21, 22 These two lines is OK, see a iterator, so concluded: at compile time the compiler will automatically convert the use of the keyword to the use of the target iterator, this is the principle of the Foreach loop. In turn, we come to two more conclusions:

1, ArrayList can use the Foreach Loop traversal, because ArrayList all the list is collection sub-interface, and collection is iterable sub-interface, The parent class of ArrayList Abstractlist correctly implements the iterator method of the Iterable interface. I wrote it myself before. ArrayList directly to the null pointer exception with a foreach loop because I wrote it myself. ArrayList does not implement Iterable interface

2, any set, whether it is provided by the JDK or write their own, as long as you want to use the Foreach Loop traversal, you must correctly implement the Iterable interface

In practice, this is the iterator pattern in design mode in 23.

What about the array?

The above is finished, good understanding, but do not know whether people have doubts, at least I have a question: the array does not implement the Iterable interface Ah, why arrays can also be used in the Foreach Loop traversal it? First give a piece of code, and then decompile:

public static void Main (string[] args) {    int[] ints = {1,2,3,4,5};            for (int i:ints)        System.out.println (i);}

Also decompile and look at the key information:

1          0:iconst_2 2          1:newarray       int 3          3:dup 4          4:iconst_0 5          5:iconst_1 6          6:iastore 7          7:dup 8          8:iconst_1 9          9:iconst_210         10:iastore11         11:astore_112         12:aload_113         13:dup14         14:astore        515         16:arraylength16         17:istore        417         19:iconst_018         20:istore_319         21 : Goto          3920         24:aload         521         26:iload_322         27:iaload23         28:istore_224         29:getstatic     #16                 //Field java/lang/system.out:ljav25 a/io/printstream;26         32:iload_227         33:invokevirtual #                 //Method java/io/printstream.prin28 tln: (I) V29         36:iinc          3,         39:iload_331         40:iload         432         42:if_icmplt     2433         45:return

This is the complete main function corresponding to the 45 bytecode directive, because this involves some compression stack, stack, push and so on some of the computer's original rational content and the knowledge of these bytecode instructions need some knowledge of C + +, so it is not explained. After a simple control of the bytecode instruction table, my personal understanding of these 45 bytecode is that Java converts the Foreach loop for the array to a circular reference to each of the arrays .

The second part of the content from: http://www.cnblogs.com/xrq730/p/4868465.html

Java:foreach Implementation principle

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.