我正在使用java中的链表实现堆栈。问题是,当下面没有元素时,我会收到 nullPointerException,例如StackNode.link 不存在。因此,如果我尝试分配 StackNode.link 我会得到异常。
使用 if 语句仅运行代码(如果存在),我只是在 if 语句中得到异常。我该怎么办?
int pop() {
StackNode temp = top;
// update top
top = belowTop;
belowTop = top.link; // this is where I get the nullPointExcpetion
return temp.data;
}
我希望当 top.link 不存在(例如为 null)时,belowTop 将为 null。这很好,但正如所描述的那样,我得到了异常(exception)。
编辑:这是我在 if 语句中尝试过的
if (top.link != null) {
belowTop = top.link;
}
else {
belowTop = null;
}
最佳答案
您需要检查变量top
是否已初始化:
...
if (top != null) {
belowTop = top.link;
} else {
// Handle the not initialized top variable
}
...
可能一个好的解决方案是如果 belowTop
未初始化,则抛出运行时异常,例如
...
if (top == null) {
throw new IllegalStateException("Can't pop from an empty stack");
}
belowTop = top.link;
...
在这种情况下,您还必须准备一个方法来检查堆栈是否不为空或未初始化。这是完整的提案:
public boolean isEmpty() {
// Your logic here
}
// Better have a public access because it seems an utility library and
// it should be accessed from anywhere
public int pop() {
StackNode temp = top;
// update top
top = belowTop;
if (top == null) {
throw new IllegalStateException("Can't pop from an empty stack");
}
belowTop = top.link; // Now it works
return temp.data;
}
您可以按如下方式使用它:
if (!myStack.isEmpty()) {
int value = myStack.pop();
// Do something
}
关于java - 我怎样才能仅引用一个确实存在的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805550/