java - 我怎样才能仅引用一个确实存在的对象?

标签 java if-statement linked-list nullpointerexception

我正在使用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/

相关文章:

创建链接列表会出现段错误(核心转储)错误

java - 具有行数据网关的注册表模式

java - 有没有办法将版本号放入 XStream 生成的 XML 中?

swift - 在 Swift 中减少 "if statements"(可能使用三元运算符)

c - 在链表中插入和删除节点

C:结构语法链表

java - 为什么临时变量与我从 arraylist.get 中得到的不一样?

java - 如何将数组放在 React Native 桥中的 WritableMap 对象上

java - 检查用户决定是否正确

MySQL - 将单词添加到文本列的末尾