【发布时间】:2015-03-19 10:05:05
【问题描述】:
我有一个问题。我知道如果我的堆栈已满,我必须分配一个双倍大小的新堆栈。我尝试使用临时堆栈,但在编译过程中,我在 55 行看到错误。错误是“无法在数组类型 E[] 上调用 push(E)”。我不知道为什么我不能这样做。
package stack;
import exception.EmptyStackException;
import exception.FullStackException;
public class ArrayStack<E> implements Stack<E>{
protected int capacity;
protected static final int CAPACITY = 1000;
protected E S[];
protected int top = -1;
@SuppressWarnings("unchecked")
public ArrayStack(int capacity){
this.capacity = capacity;
this.S = (E[]) new Object[this.capacity];
}
public ArrayStack(){
this(CAPACITY);
}
@Override
public int size() {
return top+1;
}
@Override
public boolean isEmpety() {
return (this.top < 0);
}
@Override
public E top() throws EmptyStackException {
if(isEmpety())
throw new EmptyStackException("Stack Vuoto.");
return this.S[top];
}
@Override
public void push(E element) throws FullStackException, EmptyStackException {
if(size() == capacity){
this.tempStack();
}
//throw new FullStackException("Stack Pieno.");
this.S[++top] = element;
}
private void tempStack(){
E tempS[] = (E[]) new Object[this.capacity];
E tempEl;
while(isEmpety()){
tempEl = this.pop();
tempS.push(this.pop());
}
this.capacity += this.capacity;
this.S = null;
this.S = (E[]) new Object[this.capacity];
}
public void union(Stack<E> s){
}
@Override
public E pop() throws EmptyStackException {
E element;
if(isEmpety())
throw new EmptyStackException("Stack Vuoto.");
element = S[top];
this.S[top--] = null;
return element;
}
}
【问题讨论】:
-
我们也不知道,你为什么要在
array对象上调用不存在的方法push。
标签: java data-structures stack