作爲練習練習,我創建了自己的泛型類,基本上是ArrayList
的副本。雖然與JUnit
測試的類,我遇到一個NullPointerException
錯誤添加方法:創建類ArrayList類時的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());
}
好,'this'不能'null',所以'data'必須是吧? –