【问题标题】:Why is this ArrayListStack throwing an EmptyStackException when it does contain elements?为什么这个 ArrayListStack 在包含元素时会抛出 EmptyStackException?
【发布时间】:2016-07-22 18:32:48
【问题描述】:

我很困惑为什么当我将元素推入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);
    }
}

【问题讨论】:

  • this 中的this.size() == 0; 是什么?
  • 有一个size()方法简单的返回size
  • 好的,我不确定这个类是否可以扩展 Arraylist

标签: java exception arraylist stack throw


【解决方案1】:

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

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

你的

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

检查应移至pop() 方法。

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

顺便说一句,empty() 中也有错误。 this.size() == 0 应该是 list.size() == 0

【讨论】:

    【解决方案2】:

    因为在您使用代码将第一个元素放入数组的那一刻

    list.push('A');
    

    它将抛出该异常,因为那时数组将为空。

    理想情况下,您应该在尝试从数组中删除某些元素时抛出此异常,而不是在添加时。

    【讨论】:

      【解决方案3】:
       /**
       * Removes item at top of stack and returns it.
       * @return item at top of stack
       * @throws EmptyStackException
       *             if stack is empty.
       */
      public E pop() {
          if (empty())
              throw new EmptyStackException();
          E x = list.remove(0);
          return x;
      }
      /**
       * Add item at bottom of stack.
       */
       public void push(E x) {
          list.add(x);
       }
      

      当我们试图从 List 中删除/获取某些东西时,应该抛出 EmptyStackException。注意:上面的代码不是线程安全的,如果多个线程尝试并行推送和弹出。然后输出与预期不同。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-17
        • 2015-11-19
        • 1970-01-01
        • 2010-11-09
        • 1970-01-01
        • 1970-01-01
        • 2013-12-07
        • 1970-01-01
        相关资源
        最近更新 更多