作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我很困惑为什么当我将元素插入 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/
我很困惑为什么当我将元素插入 ArrayList 时会抛出异常...这一定是我的 Push() 的问题方法,有人能找到问题吗?我尝试在 if 语句周围加上大括号,但没有成功,甚至可能是 empty()
我是一名优秀的程序员,十分优秀!