【发布时间】:2020-12-30 12:45:39
【问题描述】:
我正在测试我拥有的这个堆栈实现(使用链表),到目前为止,只要堆栈不为空,我在推送、弹出和查看时都没有遇到任何问题。
但是,当我尝试使用带有空数组的 EmptyStackException 的 try catch 块运行此代码时,它不会捕获。
当我运行这个时:
public class Run {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
//test empty stack
if(stack.isEmpty())
System.out.println("1");
try {
stack.pop();
} catch (EmptyStackException e) {
System.out.println("2");
}
}
}
打印出“1”,然后出现NullPointerException。
这是我的代码中负责从堆栈中弹出项目的部分:
public Item pop() throws EmptyStackException{
s--;
Item prevFirst = first.item;
first = first.next;
return firstVal;
}
我在这里做错了吗?
【问题讨论】:
标签: java linked-list nullpointerexception stack