作为练习,我正在创建自己的泛型类,它基本上是 ArrayList
的副本。在使用 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++;
}
在类里面胡思乱想之后,我无法弄清楚错误是从哪里来的。我可以提供任何需要的细节/类(class)的其他部分。关于问题出在哪里的任何指导都会很棒。谢谢。
类的构造函数:
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());
}
最佳答案
T[] data = (T[]) new Object[startSize];
初始化局部变量data
。你不想要的。
将其更改为以下以确保初始化实例变量 -
this.data = (T[]) new Object[startSize];
关于java - 创建类似 ArrayList 的类时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12444122/