Java For-eachの実現原理

4017 ワード

参考:
http://blog.csdn.net/a596620989/article/details/6930479
http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work
http://www.leepoint.net/notes-java/flow/loops/foreach.html
以上のいくつかの参考の招待状の中で、この話の最も簡潔で明瞭です。下記の通り抜粋します
For-each ループ
Purpose
The baic for loop was extens in Java 5 to make iteration over arrays and other collection s more convent.This newer for statement is caled the enhanced for or for-each (because it is caled this in other programming langages).I've also heard it caled the for-i n loop.
Use it in preference to the standard for loop if apple because it's mucmore readable.
Series of values.The for-each loop is used to access each success value in a collection of values.
Arays and Collection.It's commonly used to iterate over an array or a Collection s class(eg,ArayList)
Iterable.It can also iterate over anything implemens the Iterable インターフェース(must define iterator() method.Many of the Collection s clases(eg、  ArrayList)implement Iterable,which makes thefor-each loop very useful.You can also implement Iterable for your own data structures.
General Form
The for-each and equivalent for statemens have these forms.The two baic equivalent forms arven,depending one whether it is an array or an Iterable that is being traversed.In both cases an extra variable is required、an index for the array and an iterator for the collection.
【yasi】ここで私たちは次の事実を知るだけでいいです。
  • For-each構文の内部では、collectionはneted iteratotionで実現され、対配列は下付き遍で従来から実現されてきた。
  • Java 5および以上のコンパイラは、iterationおよび下付きエルゴードに基づく内部実装を隠す。(注意してください。ここで言うのは「Javaコンパイラ」です。あるいはJava言語は、Javaコードの一部ではなく、その実装を隠しています。つまり、どのJDKのJavaコードにもここに隠れた実現が見つかりません。ここの実現は、Javaコンパイラに隠れています。このように、For-eachのJavaコードがコンパイルされたバイトコードを確認するしかないかもしれません。これは一体どうやって実現されたのかを推測します。
    以下では「For-each」と「その対等なiteration/index実現」の対比を簡潔に明らかにします。
    For-each loop
    Equivalent for loop
    for (type var : arr) {
        body-of-loop
    }
    for (int i = 0; i < arr.length; i++) { 
        type var = arr[i];
        body-of-loop
    }
    for (type var : coll) {
        body-of-loop
    }
    for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
        type var = iter.next();
        body-of-loop
    }
    Example-Adding all elemens of an array
    Here is a loop written as both a for-each loop and a baic 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 is the same loop using the baic 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 successively.
        sum += ar[i];
    }
    Where the for-each is apris
    【yasi】For-eachは万能ではないので、次の場合はFor-eachを使うには不向きです。
    Altho the enhanced for loop can make code much clearer,it can't be used in some comon situations.
    For-eachを使う時は、collectionや配列中の要素に対して幅操作ができません。
  • Only access.Elements can not be assigned to,eg,not to increment each element in a collection. 
  • 同時に、1つのcollectionまたは行列だけを巡回することができます。複数のcollectionまたは行列を同時に遍歴することはできません。
  • Only single structure.It's not possible to trverse two structures.eg,to comparse two arrays.
  • 巡回中に、collectionまたは配列の中で同時に一つの要素しか見えません。すなわち「現在遍歴している要素」だけが見られます。前の要素または後の要素は見えません。
  • Only single element.Use only for single element access,eg,not to compre success.
  • 右回りしかできません。逆遍歴はできません。(比べて、C+++STLには、reversecuterator、rbegin()、rend()などがあります。逆遍歴もできます。)
  • Only forward.It's possible to iterate only forward by single steps.
  • Java 5に対応する前のJavaバージョンでは、For-eachは使えません。
  • At least Java 5.Don't use it if you need comptibility with versions before Java 5.