我必須實現一個通用堆棧,但是當我嘗試構建項目時,我遇到了一個我無法弄清楚的錯誤。下面的代碼:通用堆棧陣列
Stack.java - >接口
package stack;
public interface Stack <T> {
public boolean isEmpty();
public boolean isFull();
public void push(T x) throws StackFullException;
public boolean offer(T x);
public T pop() throws StackEmptyException;
public T poll();
public T peek() throws StackEmptyException;
public T element();
}
StackArray.java - >接口
package stack;
public class StackArray <T extends Number> implements Stack {
static int max;
private int nr;
private T[] stack;
public StackArray(int size){
nr=0;
stack=(T[])(new Object[size]);
max=size;
}
public boolean isEmpty() {
if (nr<=0)
return true;
return false;
}
public boolean isFull() {
if (nr==max-1)
return true;
return false;
}
public void push(Object x) throws StackFullException{
if(isFull())
throw new StackFullException();
else
stack[nr++]=(T)x;
}
public boolean offer(Object x) {
if(isFull())
return false;
else
{
stack[nr++]=(T)x;
return true;
}
}
public T pop() throws StackEmptyException {
T aux=(T)(new Object());
if(isEmpty())
throw new StackEmptyException();
else
{
aux=stack[nr];
stack[nr]=null;
nr--;
return aux;
}
}
public T poll() {
T aux=(T)(new Object());
if(isEmpty())
return null;
else
{
aux=stack[nr];
stack[nr]=null;
nr--;
return aux;
}
}
public T peek() throws StackEmptyException {
if(isEmpty())
throw new StackEmptyException();
else
return stack[nr];
}
public T element() {
if(isEmpty())
return null;
else
return stack[nr];
}
}
和主類的實現:
package stack;
public class Main {
public static void main(String[] args) throws StackFullException, StackEmptyException {
StackArray stiva=new StackArray(10);
for(int i=1; i<10; i++)
stiva.push(i);
for(int i=1; i<10; i++)
System.out.print(stiva.pop()+" ");
}
}
當我嘗試構建該項目時,我收到以下錯誤:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Number;
at stack.StackArray.<init>(StackArray.java:10)
at stack.Main.main(Main.java:5)
Java Result: 1
任何人都可以幫助我嗎?謝謝!
另一件事;似乎沒有'max'爲空的好理由;事實上,如果人們一次使用你的堆棧的兩個實例,你的代碼可能會非常災難性地失敗。 – 2011-03-14 01:59:07
您不想使用[Stack] [1]或[Deque] [2]的實現的任何特定原因? [1]:http://download.oracle.com/javase/6/docs/api/java/util/Stack.html [2]:http://download.oracle.com /javase/6/docs/api/java/util/Deque.html – 2011-03-14 01:09:59