練習問題として、基本的に のコピーである独自のジェネリック クラスを作成していますArrayList
。でクラスをテストしているときに、add メソッドでエラーが発生しましたJUnit
。NullPointerException
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());
}