在使用add方法时,出现空指针异常。
对照了老师的您的代码,好象没有区别。
但还是出现了空指针异常,麻烦帮忙看看是什么原因。

相关代码:
public class Main {
public static void main(String[] args) {
Array<Integer> arr = new Array<>();
for (int i = 0; i < 10; i++) {
arr.addLast(i);
}
System.out.println(arr);
}
}相关代码:
public class Array<E> {
private E[] data;
private int size;
public Array(int capacity) {
E[] data = (E[]) new Object[capacity];
size = 0;
}
public Array() {
this(10);
}
public int getCapacity() {
return data.length;
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void add(int index, E e) {
if (index < 0 || index > size) {
throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size.");
}
if (size == data.length) {
resize(2 * data.length);
}
for (int i = size; i > index; i --) {
data[i] = data[i - 1];
}
data[index] = e;
size ++;
}
public void addFirst(E e) {
add(0, e);
}
public void addLast(E e) {
add(size, e);
}
public E get(int index) {
if (index < 0 || index >= size) {
throw new IllegalArgumentException("Get failed. Index is illegal.");
}
return data[index];
}
public void set(int index, E e) {
if (index < 0 || index >= size) {
throw new IllegalArgumentException("Set failed. Index is illegal.");
}
data[index] = e;
}
public boolean contains(E e) {
for (int i = 0; i < size; i++) {
if (data[i].equals(e)) {
return true;
}
}
return false;
}
public int find(E e) {
for (int i = 0; i < size; i++) {
if (data[i].equals(e)) {
return i;
}
}
return -1;
}
public E remove(int index) {
if (index < 0 || index >= size) {
throw new IllegalArgumentException("Remove failed. Require index >= 0 and index < size.");
}
E ret = data[index];
for (int i = index; i < size; i++) {
data[i] = data[i + 1];
}
data[size - 1] = null;
size --;
if (size == data.length / 4 && data.length / 2 != 0) {
resize(data.length / 2);
}
return ret;
}
public E removeFirst() {
return remove(0);
}
public E removeLast() {
return remove(size - 1);
}
public void removeElement(E e) {
int index = find(e);
if (index != -1) {
remove(index);
}
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append(String.format("Array:size = %d , capacity = %d\n", size, getCapacity()));
res.append('[');
for (int i = 0; i < size; i++) {
res.append(data[i]);
if (i < size - 1) {
res.append(", ");
}
}
res.append(']');
return res.toString();
}
private void resize(int newCapacity) {
if (newCapacity < size) {
throw new IllegalArgumentException("Resize is failed. require newCapacity >= size.");
}
E[] newData = (E[]) new Object[newCapacity];
for (int i = 0; i < size; i++) {
newData[i] = data[i];
}
data = newData;
}
}9
收起
正在回答 回答被采纳积分+1
1回答
liuyubobobo
2024-09-17 09:54:59
构造函数中的
public Array(int capacity) {
E[] data = (E[]) new Object[capacity];
size = 0;
}应该改成:
public Array(int capacity) {
data = (E[]) new Object[capacity];
size = 0;
}否则你在构造函数中新声明了一个局部变量 data,并为其开辟了空间,在构造函数结束后,这个局部变量的生命周期就结束了,空间自动释放。整个过程没有为类成员变量 data 开辟空间。
继续加油!:)
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星