gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:15:03 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com