有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数据结构Java堆栈无法在数组类型E[]上调用push(E)

我有个问题。我知道如果我的堆栈已满,我必须分配一个两倍大小的新堆栈。我曾尝试使用临时堆栈,但在编译过程中,我在55行上看到一个错误。错误为“无法对数组类型E[]调用推送(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;
}

}

共 (2) 个答案

  1. # 1 楼答案

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

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

  2. # 2 楼答案

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

    tempS是一个数组,而不是堆栈,因此不能对其调用push方法