5

Oracle Java SE チュートリアルからの別の例。正常に動作しますが、内部クラスのインスタンスを作成するときに「this」が必要かどうか、またはなぜ必要なのかわかりません。抜いても抜いても結果は変わらないようです。

明確にするために、私は以下を参照しています: InnerEvenIterator iterator = this.new InnerEvenIterator(); // 'this' を使用する理由がわからない

public class DataStructure {
    // create an array

    private final static int SIZE = 15;
    private int[] arrayOfInts = new int[SIZE];

    public DataStructure() {
        // fill the array with ascending integer values
        for (int i = 0; i < SIZE; i++) {
            arrayOfInts[i] = i;
        }
    }

    public void printEven() {
        // prints out the value of even indices in the array
        InnerEvenIterator iterator = this.new InnerEvenIterator(); // not sure why using 'this'
        while (iterator.hasNext()) {
            System.out.println(iterator.getNext() + " ");
        }
    }

    // inner class implements the Iterator pattern
    private class InnerEvenIterator {
        // start stepping through the array from the beginning

        private int next = 0;

        public boolean hasNext() {
            // check if a current element is the last in the array
            return (next <= SIZE - 1); // -1 b/c dealing with array's length.
        }

        public int getNext() {
            // record a value of an even index of the array
            int retValue = arrayOfInts[next];
            // get the next even element
            next += 2;
            return retValue;
        }
    }

    public static void main(String s[]) {
        // fill the array with integer values and print out only
        // values of even indices
        DataStructure ds = new DataStructure();
        ds.printEven();
    }
}
4

3 に答える 3

10

この場合、は必要ありませんthis.。ただし、内部クラスは常に囲んでいるインスタンスを使用して構築する必要があるため、これはthis.単純に読者に明確に示されています。

の非静的メソッドの内部にいないDataStructure場合 (つまり、thisが存在しない場合、または のインスタンスでない場合)、を作成するときにDataStructureのインスタンスを実際に指定する必要があります。DataStructureInnerEvenIterator

InnerEvenIterator iterator = dataStructure.new InnerEvenIterator();
于 2013-08-19T03:34:48.943 に答える