3 回答

TA貢獻1824條經驗 獲得超8個贊
第一行只是一種優化,旨在如果兩個引用都指向同一對象,則提前返回結果。
可以price為空嗎?我認為是的,因為您正在實施中檢查它equals()。在這種情況下,您的代碼將無法工作,以防other.price萬一null。具體這里的代碼:
price.compareTo(other.price) != 0
會拋出一個NullPointerException.
你可以這樣修復它:
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // is this right or should this be deleted
if (obj == null || getClass() != obj.getClass()) return false;
final MyProduct other = (MyProduct) obj;
// If you prefer, the below two can be replaced with a single condition
// price != null ^ other.price != null
// Credits to @Andreas
if (price == null && other.price != null) {
return false;
}
if (price != null && other.price == null) {
return false;
}
if (other.price != null && price.compareTo(other.price) != 0) {
return false;
}
return super.equals(obj);
}
現在,您可能可以將其縮短,但我個人認為這種方式最具可讀性。
無論如何,除非您真的非常關心自定義您的equals()實現,否則我建議您使用 IDE 生成一個并堅持使用它。他們大多數時候都做得不錯,你不必擔心它會被破壞(盡管比較對BigDecimals他們來說可能很棘手,因為你不關心規模而只關心價值)。

TA貢獻1806條經驗 獲得超5個贊
我編寫了一個 utitly 方法,可用于比較兩個 BigDecimals 而不會拋出 NPE:
// returns true, if val1 is the same as val2
// can this be improved ?
public static boolean isEqual(BigDecimal val1, BigDecimal val2) {
return !((val1 != null ^ val2 != null) || (val2 != null && val1.compareTo(val2) != 0));
}
這可以在 equals 方法中使用:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
final MyProduct other = (MyProduct) obj;
if(!isEqual(price, other.price)) return false;
return super.equals(obj);
}

TA貢獻1880條經驗 獲得超4個贊
我找到了最簡單的方法:
public static boolean isEqual(BigDecimal val1, BigDecimal val2) {
return val1 != null ^ val2 != null && val2 != null && val1.compareTo(val2) != 0;
}
然后在 equals() 中使用它:
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
final MyProduct other = (MyProduct) obj;
if(!isEqual(price, other.price)) return false;
return super.equals(obj);
}
添加回答
舉報