我正在尝试在动态数组上实现pop方法。它应该将数组复制到一个少一个元素的新数组。但是我收到了错误。如果我删除代码'data [data.length] = 0;'错误消失但数组的长度不会改变。
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:100 在DynamicArray.pop(DynamicArray.java:37) 在DynamicArray.main(DynamicArray.java:55)
import java.util.Arrays;
public class DynamicArray {
private static final int SIZE_FACTOR = 5;
private int size;
private int index;
private int[] data;
public DynamicArray(int size) {
this.data = new int[size];
}
public int length() {
return size;
}
public int select(int k) {
return data[k];
}
public void store(int o, int k) {
data[k]=o;
}
public void push(int o) {
if(data.length==size) {
extend();
}
size++;
data[index++] = o;
}
public int pop() {
data[data.length] = 0;
data = Arrays.copyOf(data, data.length-1);
size--;
return data.length;
}
private void extend() {
data = Arrays.copyOf(data, data.length+SIZE_FACTOR);
System.out.println("New length: " + data.length);
}
public static void main(String args[]) {
DynamicArray a = new DynamicArray(10);
for (int i = 1; i <= 100; i++) {
a.push(i);
}
System.out.println(a.length());
System.out.println(a.select(99));
a.pop();
}
}