簡體   English   中英

僅當 object 實際存在時,我如何才能引用它?

[英]How can I only refer to an object ONLY if it actually exists?

我正在使用 java 中的鏈表實現一個堆棧。 問題是當下面沒有元素時我得到一個 nullPointerException,例如 StackNode.link 不存在。 因此,如果我嘗試分配 StackNode.link,我會得到異常。

使用 if 語句僅在代碼存在時運行代碼,我只是在 if 語句中得到異常。 我該如何 go 關於這個?

int pop() {

    StackNode temp = top;

    // update top
    top = belowTop;
    belowTop = top.link; // this is where I get the nullPointExcpetion


    return temp.data;

}

我希望當 top.link 不存在(例如為空)時,belowTop 將只是 null。 這很好,但正如我所描述的,我得到了例外。

編輯:這是我用 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
}

試一試:

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

以上檢查top.link是否為null,這是一個有效的檢查,不會導致nullPointerException。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM