Java 创建类似ArrayList的类时出现NullPointerException
作为实践练习,我正在创建自己的泛型类,它基本上是Java 创建类似ArrayList的类时出现NullPointerException,java,junit,arraylist,abstract,Java,Junit,Arraylist,Abstract,作为实践练习,我正在创建自己的泛型类,它基本上是ArrayList的副本。在使用JUnit测试类时,我在add方法中遇到了NullPointerException错误: public void add(int index, T element) { if (index > this.size() || index < 0) { throw new IndexOutOfBoundsException(); } if (this.size() =
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++;
}
public void add(int索引,T元素){
如果(索引>此.size()| |索引<0){
抛出新的IndexOutOfBoundsException();
}
if(this.size()==data.length){
//^这是错误指向的行
调整大小(此.data);
}
for(int i=索引;i
在和全班同学闹了很久之后,我不知道错误是从哪里来的。我可以提供课堂上需要的任何细节/其他部分。任何关于问题所在位置的指导都是非常棒的。多谢各位
类的构造函数:
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];
}
MyArrayList(int startSize){
//将起始尺寸四舍五入到最接近的2次方
int-pow2=1;
做{
pow2*=2;
}而(pow2
以下测试用例测试大小,但在尝试添加元素时遇到错误:
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());
}
public void testSize(){
MyArrayList测试=新建MyArrayList();
ArrayList real=新的ArrayList();
assertEquals(“构建后的大小”、real.Size()、test.Size());
试验。添加(0,5);
加上(0,5);
assertEquals(“添加后的大小”、real.Size()、test.Size());
}
I NPE在您提到的线路上,这只是因为数据为空。您在哪里初始化数据
可能在创建CustomArrayList
时,您没有初始化内部数组数据
数据
初始化是问题所在。它应该是this.data=(T[])新对象[startSize]
我NPE在您提到的线路上,这只是因为数据
为空
。您在哪里初始化数据
T[] data = (T[]) new Object[startSize];
可能在创建CustomArrayList
时,您没有初始化内部数组数据
数据
初始化是问题所在。它应该是this.data=(T[])新对象[startSize]代码>
T[] data = (T[]) new Object[startSize];
它初始化局部变量数据
。你不想要的
将其更改为以下,以确保初始化实例变量-
this.data = (T[]) new Object[startSize];
它初始化局部变量数据
。你不想要的
将其更改为以下,以确保初始化实例变量-
this.data = (T[]) new Object[startSize];
嗯,这个
不能是空的
,所以数据
必须是,对吗?嗯,这个
不能是空的
,所以数据
必须是,对吗?数据在构造函数中,我编辑了原始帖子以添加到构造函数中,你可以发布构造函数和测试用例吗?数据在构造函数中,我编辑了原始帖子以添加构造器您可以发布构造器和测试用例吗?+1这是打开(并注意)关于未使用变量的警告的时候。+1这是打开(并注意)关于未使用变量的警告的时候。