Java 堆栈无法对数组类型 E[] 调用 push(E)

Java Stack Cannot invoke push(E) on the array type E[]

我有个问题。我知道如果我的堆栈已满,我必须分配一个双倍大小的新堆栈。我曾尝试使用临时堆栈,但在编译期间,我在 55 行看到错误。错误是 "Cannot invoke push(E) on the array type 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;
}

}

tempS 不是 Stack,因此您不能为此变量调用 Stack 的方法。

你的tempStack方法应该做的可能是创建一个更大容量的数组,将this.S复制到新数组并将该数组分配给this.S

E tempS[] = (E[]) new Object[this.capacity];

tempS 是一个数组而不是 Stack 所以你不能在它上面调用 push 方法