这是我的全部代码,问题需要我使用数组来解决。
import java.lang.reflect.Array;
public class MyStack<T> {
public MyStack (Class<T[]> _class,int size){
final T[] values = (T[]) Array.newInstance(_class,size);
this.values = values;
this.size=size;
}
private T[] values;
private int top=0,size;
public void push(T nextElement){
if(isFull()){
System.out.println("full");
}
else {
values[top++] = nextElement;
}
}
public T pop(){
if(isEmpty()) {
System.out.println("empty");
return null;
}
else {
return values[top--];
}
}
public boolean isEmpty(){
if (top==0)return true;
return false;
}
public boolean isFull(){
if(top==size-1)return true;
else return false;
}
public static void main(String args[]){
MyStack<Integer> myStack = new MyStack<Integer>(Integer[].class,9);
for (int i =0;i<10;i++)
{
myStack.push(i);
}
while(!myStack.isEmpty()){
System.out.println(myStack.pop());
}
}
}
当我编译它时,它会在 values[top++] = nextElement;
处抛出 Exception in thread "main"java.lang.ArrayStoreException: java.lang.Integer我使用 String、Integer 或任何其他对象的类型。
有办法解决这个问题吗?
最佳答案
您的构造函数采用 Class<T[]>
但应该采取 Class<T>
,你也不需要 values
上的变量阴影。我会这样写
public MyStack(Class<T> _class, int size) {
this.values = (T[]) Array.newInstance(_class, size);
this.size = size;
}
您不需要if else
链条isEmpty
(直接返回你正在测试的条件) - 就像
public boolean isEmpty() {
return top == 0;
}
或者isFull
public boolean isFull() {
return top == size - 1;
}
关于java - 将对象存储到数组时线程 "main"java.lang.ArrayStoreException 中出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42883707/