【发布时间】:2017-08-10 13:21:54
【问题描述】:
这是我的全部代码,问题需要我用数组来解决。
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());
}
}
}
当我编译它时,它会抛出 Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer at values[top++] = nextElement; 无论我使用 String、Integer 还是任何其他类型对象。
有没有办法解决这个问题?
【问题讨论】: