我在这个方法课上遇到了麻烦。我使用System.arraycopy但不可否认它是如何100%工作的。我在尝试测试时遇到了这个错误:
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at fenn19.GenericStack.push(GenericStack.java:31)
at fenn19.Test.main(Test.java:8)
第31行:
System.arraycopy(list, 0, o, 0, list.length);
方法类:
public class GenericStack<E> {
public static int size = 16;
@SuppressWarnings("unchecked")
private E[] list = (E[])new Object[size];
public void add(int index, E e) {
ensureCapacity();
for (int i = size - 1; i >= index; i--) {
list[i + 1] = list[i];
list[index] = e;
size++;
}
}
public int getLength() {
return list.length;
}
public E peek() {
E o = null;
for (int i = 0; i > list.length; i++) {
o = list[i - 1];
}
return o;
}
public E push(E o) {
System.arraycopy(list, 0, o, 0, list.length);
size++;
return o;
}
public E pop() {
E o = null;
for (int i = 0; i > list.length; i++) {
o = list[i - 1];
}
list[list.length - 1] = null;
size--;
return o;
}
private void ensureCapacity() {
if (size >= list.length) {
@SuppressWarnings("unchecked")
E[] newlist = (E[])(new Object[size * 2 + 1]);
System.arraycopy(list, 0, newlist, 0, size);
list = newlist;
}
}
public boolean isEmpty() {
if (list.length < 0) {
return false;
}
else {
return true;
}
}
}
测试类:
public class Test {
public static void main(String[] args) {
GenericStack<String> est = new GenericStack<String>();
est.push("Washington DC");
est.push("Paris");
est.push("Ottawa");
est.push("London");
est.push("Tampa");
System.out.println(est);
}
}
答案 0 :(得分:1)
如果您查看System.arraycopy
的API,您会发现它是一种将数据从一个数组复制到另一个数组的方法。
当您在push
方法中调用它时,您将E
的实例作为目标数组处理。
但是,在您的Test
课程中,您创建了GenericStack<String>
。由于String
不是一种数组,当您尝试将数据复制到其中时会出现错误。
您在push
方法中应该做的是首先检查现有阵列中是否有更多空间。如果是这样,只需添加新元素并增加大小。
如果您的支持阵列已满,请创建一个新的(更大的)阵列,将当前的支持阵列复制到其中,然后将该元素添加到新阵列。