【问题标题】:How can I only refer to an object ONLY if it actually exists?我如何才能仅在对象实际存在时才引用它?
【发布时间】:2019-11-11 16:52:43
【问题描述】:

我正在使用 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。这很好,但如上所述,我得到了例外。

编辑:这是我尝试使用 if 语句的方法

if (top.link != null) {
        belowTop = top.link;
    }
else {
        belowTop = null;
    }

【问题讨论】:

  • 您得到异常是因为top 为空,而不是因为top.link 为空。
  • 您说您尝试使用 if 语句。你能展示一下你的尝试吗?
  • @Sweeper 我更新了它:)

标签: java if-statement linked-list nullpointerexception


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    试一试:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 2019-02-06
      • 2019-05-08
      • 2013-06-14
      • 2021-08-28
      • 2012-07-21
      • 1970-01-01
      相关资源
      最近更新 更多