创建类似ArrayList的类时出现NullPointerException

use*_*050 1 java junit arraylist abstract

作为练习练习,我正在创建自己的泛型类,它基本上是一个副本ArrayList.在测试类时JUnit,我NullPointerException在add方法中遇到错误:

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++;
}
Run Code Online (Sandbox Code Playgroud)

在搞乱了很多课之后,我无法弄清楚错误的来源.我可以提供所需的任何细节/课程的其他部分.关于问题所在位置的任何指导都很棒.谢谢.

该类的构造函数:

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];
}
Run Code Online (Sandbox Code Playgroud)

以下测试用例测试大小,但在尝试添加元素时遇到错误:

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());
}
Run Code Online (Sandbox Code Playgroud)

Bhe*_*ung 6

T[] data = (T[]) new Object[startSize];
Run Code Online (Sandbox Code Playgroud)

初始化局部变量data.你不想要的.

将其更改为以下以确保初始化实例变量 -

this.data = (T[]) new Object[startSize];
Run Code Online (Sandbox Code Playgroud)