通用协议栈阵列 [英] Generic Stack Array
问题描述
我要实现一个通用的堆栈,但是当我尝试建立项目我有我想不出一个错误。这里的code:
I have to implement a generic stack, but when I try to build the project I have an error that I can't figure out. Here's the code:
Stack.java - >接口
Stack.java -> interface
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 - >的接口的实现
StackArray.java -> the implementation of the interface
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()+" ");
}
}
当我尝试建立我收到以下错误项目:
When I try to build the project I receive the following error:
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
谁能帮我?谢谢!
Can anyone help me? Thanks!
推荐答案
的删除 T []
是号码[]
因为上界 > T
是编号
。因此,你的栈
真是声明为号码[]
不是对象[]
。在你的构造你想分配对象[]
到栈
。创建一个号码[]
代替。
The erasure of T[]
is Number[]
because the upper bound of T
is Number
. Thus your stack
is really declared as a Number[]
not an Object[]
. In your constructor you are trying to assign an Object[]
to stack
. Create a Number[]
instead.
stack=(T[])(new Number[size]);
顺便说一句,你可能想
As an aside, you probably want
public class StackArray <T extends Number> implements Stack<T>
您不应该实现类的原始版本。其结果是,你需要更新其他方法(如推(T)
而不是推(对象)
)
You shouldn't implement the raw version of the class. As a consequence you'll need to update other methods (e.g. push(T)
instead of push(Object)
).
这篇关于通用协议栈阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!