簡體   English   中英

如何在Java中檢查object是否為null?

[英]How to check if object is null in Java?

檢查職位是否被占用的最佳方法是什么? 我不認為我應該使用“ this == null” ...

class Cell {
    int column;
    int row;
    char letter;

    public Cell(int column, int row, char letter) {
        super();
        this.column = column;
        this.row = row;
        this.letter = letter;
    }

    public boolean isEmpty() {
        if (this==null) return true;
        else return false;
    }
}

我將假定char是您Cell的內容,並且您想檢查該內容是否為null

首先, this永遠不能為null this是當前對象,因此始終存在。

您正在使用char因為這是一個原語也不能為null 將其更改為對象包裝,並檢查是否為null

class Cell {

    int column;
    int row;
    Character letter;

    public Cell(int column, int row, Character letter) {
        this.column = column;
        this.row = row;
        this.letter = letter;
    }

    public boolean isEmpty() {
        return letter == null;
    }
}

另一個要注意的是,默認情況下始終會調用超類構造函數,因此沒有理由調用super()

如果對象的實例存在 ,則它不能為null (如Code-Guru的評論所述)。 但是,您要嘗試的是檢查對象的letter屬性是否為null。

只是建議,不要使用char作為類型,而應使用Character ,它是封裝char類型的類。

然后,您的課程可能如下所示:

class Cell {
    int column;
    int row;
    Character letter;

    public Cell(int column, int row, Character letter) {
        super();
        this.column = column;
        this.row = row;
        this.letter = letter; // This is an object, not a primitive type 
    }

    public boolean isEmpty() {
        if (letter==null) 
            return true;
        else 
            return false;
    }
}

this不能為null因為this是您的Cell實例。 無需將char更改為Character

class Cell {
    int column;
    int row;
    char letter;

    public Cell(int column, int row, char letter) {
        super();
        this.column = column;
        this.row = row;
        this.letter = letter;
    }

    public boolean isEmpty() {
        return letter == 0;
    }
}

暫無
暫無

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

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