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