[英]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.