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