【问题标题】:NullPointerException when creating an ArrayList-like class创建类 ArrayList 类时出现 NullPointerException
【发布时间】:2012-09-16 02:57:21
【问题描述】:

作为练习,我正在创建自己的泛型类,它基本上是ArrayList 的副本。在使用JUnit 测试类时,我在add 方法中遇到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 一定是,对吧?

标签: java junit arraylist abstract


【解决方案1】:
T[] data = (T[]) new Object[startSize];

这会初始化局部变量data。你不想要的。

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

this.data = (T[]) new Object[startSize];

【讨论】:

  • +1 这是需要打开(并注意)未使用变量的警告的时候。
【解决方案2】:

我 NPE 在你提到的那一行,只是因为 datanull。你在哪里初始化data

也许当您创建 CustomArrayList 时,您并没有初始化您的内部数组 data

data 初始化是问题所在。应该是
this.data = (T[])new Object[startSize];

【讨论】:

  • 数据在构造函数中,我编辑原帖添加到构造函数中
  • 你能发布你的构造函数和测试用例吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
  • 2018-02-08
  • 2015-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多