摘要: 編寫完美equals方法的建議:
1. 顯示參數(shù)命名為otherObject
2. 測試this同otherObject是否是同一個(gè)對象:
if(this == otherObject) return ture;
3. 測試otherObject是否為null。如果是,就返回false。這個(gè)測試是必需的:if(otherObject == null) return false;
4. 測試this和otherObject是否屬于同一個(gè)類。這項(xiàng)測試是“對稱性規(guī)則”所要求的。 if(getClass() != otherObject.getClass()) return false;
5. 把otherObject的類型轉(zhuǎn)換為你的類型所屬的類型。
ClassName other = (ClassName)otherObject;
6. 最后比較所有字段。使用==比較基本類型字段,使用equals比較對象字段。
閱讀全文