我该如何仅引用对象实际存在的对象?

我正在使用Java中的链表实现堆栈。问题是当下面没有元素时,我得到一个nullPointerException。 StackNode.link不存在。因此,如果我尝试分配StackNode.link,则会收到异常。

使用if语句仅在存在的情况下运行代码,我只是在if语句中获得了Exception。我该怎么办?

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。很好,但是正如我所描述的,我得到了例外。

编辑:这是我尝试的if语句

if (top.link != null) {
        belowTop = top.link;
    }
else {
        belowTop = null;
    }
sandao9 回答:我该如何仅引用对象实际存在的对象?

您需要检查变量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
}
,

试一试:

if (top.link != null) {
    belowTop = top.link;
} else {
    //handle the exception
}

上面的代码检查top.link是否为null,这是有效的检查,不会导致nullPointerException。

本文链接:https://www.f2er.com/3122604.html

大家都在问