1

練習問題として、基本的に のコピーである独自のジェネリック クラスを作成していますArrayList。でクラスをテストしているときに、add メソッドでエラーが発生しましたJUnitNullPointerException

public void add(int index, T element) {
    if (index > this.size() || index < 0) {
        throw new IndexOutOfBoundsException();
    }

    if (this.size() == data.length) {
        // ^ This is the line that the error points to
        resize(this.data);
    }

    for (int i = index; i < this.size; i++) {
        this.data[i + 1] = this.data[i]; //fix
    }

    this.data[index] = element;
    size++;
}

クラスをいじった後、エラーの原因がわかりません。必要なクラスの詳細/その他の部分を提供できます。問題がどこにあるかについてのガイダンスは素晴らしいでしょう。ありがとうございました。

クラスのコンストラクター:

MyArrayList(int startSize) {
    // round the startSize to nearest power of 2
    int pow2 = 1;
    do {
        pow2 *= 2;
    } while (pow2 < startSize);

    startSize = pow2;
    this.size = 0;
    T[] data = (T[]) new Object[startSize];
}

次のテスト ケースはサイズをテストしますが、要素を追加しようとするとエラーが発生します。

public void testSize() {
    MyArrayList<Integer> test = new MyArrayList<Integer>(); 
    ArrayList<Integer> real = new ArrayList<Integer>();
    assertEquals("Size after construction", real.size(), test.size());
    test.add(0,5);
    real.add(0,5);
    assertEquals("Size after add", real.size(), test.size());
}
4

2 に答える 2

6
T[] data = (T[]) new Object[startSize];

これにより、ローカル変数が初期化されますdata。あなたが望まないもの。

インスタンス変数を確実に初期化するために、次のように変更します -

this.data = (T[]) new Object[startSize];
于 2012-09-16T03:11:24.043 に答える
0

私はNPEがあなたが言ったライン上にあるのは、それが理由だけdataですnull。どこで初期化していdataますか?

たぶん、あなたがあなたを作成しているとき、あなたはCustomArrayListあなたの内部配列を初期化していないでしょうdata

data初期化が問題です。そのはず
this.data = (T[])new Object[startSize];

于 2012-09-16T03:05:11.577 に答える