java - 为什么这个 ArrayListStack 在包含元素时抛出 EmptyStackException?

标签 java exception arraylist stack throw

我很困惑为什么当我将元素插入 ArrayList 时会抛出异常...这一定是我的 Push() 的问题方法,有人能找到问题吗?我尝试在 if 语句周围加上大括号,但没有成功,甚至可能是 empty() 方法有问题?

这是异常消息:

Exception in thread "main" java.util.EmptyStackException
    at ArrayListStack.push(ArrayListStack.java:35)
    at StackMain.main(StackMain.java:7)

代码:

public class ArrayListStack<E> implements Stack<E> {
    // ArrayList to store items
    private ArrayList<E> list = new ArrayList<E>();

    public ArrayListStack() {
    }

    /**
     * Checks if stack is empty.
     * @return true if stack is empty, false otherwise.
     */
    public boolean empty() {
        return this.size() == 0;
    }

    /**
     * Removes item at top of stack and returns it.
     * @return item at top of stack
     * @throws EmptyStackException
     *             if stack is empty.
     */
    public E push(E x) {
        if (empty())
            throw new EmptyStackException();
        list.add(x);
        return x;
    }

//MAIN METHOD
public class MainStack {

    public static void main(String[] args) {

        ArrayListStack<Character> list = new ArrayListStack<>();
        list.push('A');
        list.push('B');
        list.push('C');
        System.out.print(list);
    }
}

最佳答案

push() 当堆栈为空时不应抛出异常,因为在压入第一个元素之前堆栈将是空的,这很好。

当前,您的第一个 push (list.push('A')) 正在抛出异常,因为堆栈为空。从push 中删除该条件。如果您的堆栈对元素数量有限制,则您应该在 push 中设置一个条件,在堆栈已满时抛出异常。

你的

    if (empty())
        throw new EmptyStackException();

check 应移至 pop() 方法。

编辑:push()方法的Javadoc实际上描述了一个pop()逻辑,它删除堆栈顶部的元素并返回它。在 pop() 中,您的空支票是正确的。

顺便说一句,您在 empty() 中也遇到了错误。 this.size() == 0 应该是 list.size() == 0

关于java - 为什么这个 ArrayListStack 在包含元素时抛出 EmptyStackException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36381953/

相关文章:

c# - XElement.Parse NotSuportedException

C++ 异常访问冲突

delphi - 如何在一条语句中将 ListBox 中的对象分配给 ArrayList?

java - 在 Polygot 架构中将 Google Cloud Endpoints 与 Cloud SQL 和 Cloud DataStore 结合使用

java - 如何在java中使我的文本字段更大以适应GUI

java - 自动装箱:所以我可以写:Integer i = 0;而不是:整数 i = 新整数(0);

java - IBM JRE : validate DOMSource with xsd doesn't work

c# - 为什么在不应该抛出该异常时抛出该异常?

java - 如何将一个值从一个 ArrayList 移动到另一个

java - 为什么 list.get(0).equals(null) 不起作用?