【问题标题】:Java Stack Cannot invoke push(E) on the array type E[]Java Stack 无法在数组类型 E[] 上调用 push(E)
【发布时间】: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


【解决方案1】:

tempS 不是Stack,所以你不能为这个变量调用Stack 的方法。

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

【讨论】:

  • if(size() == capacity){ this.capacity += this.capacity; E tempS[] = (E[]) new Object[this.capacity]; tempS = this.S;这.S = null; this.S = (E[]) new Object[this.capacity];这.S = tempS;当我在 tempStack 中复制 this.S 时,大小仍然是旧大小
  • @MarcoFerraioli tempS = this.S 不会将 this.S 复制到 tempS,它只是复制参考。您应该使用 Arrays.copyOf 将原始数组的元素复制到目标数组。
【解决方案2】:
E tempS[] = (E[]) new Object[this.capacity];

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

【讨论】:

    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 2014-05-16
    • 1970-01-01
    • 2011-03-09
    • 2014-12-08
    • 1970-01-01
    相关资源
    最近更新 更多