1. 程式人生 > >重寫equals方法的建議

重寫equals方法的建議

在Objdect類中,equals方法用於檢測兩個物件是否具有相同的引用。因此equals方法也常常被各種類重寫,下面給出一些重寫equals方法的建議:

1)將引數命名為otherObject。

2)比較this和otherObject是否引用同一個物件:

if(this == otherObject)    return true;

3)比較otherObject是否為null,如果為null,返回false:

if(otherObject == null)    return false;

4)比較thi和otherObject是否屬於同一個類。

   如果equals方法在每個子類中有所改變,就使用getClass檢測:

if(getClass != otherObject.getClass())    return false;

   如果equals方法在每個子類中都是統一的語義,就使用instanceof檢測:

if(!(otherObject instanceof ClassName))    return false;

5)將otherObject轉換為對應的類型別量,針對需求選取特定的域進行比較。使用==比較基本型別域,使用equals比較物件域。如果所有域都匹配,則返回true,否則返回false。如果在子類中重新定義equals,要在其中包含super.equals(otherObject)。

ClassName other = (ClassName)otherObject;
super.equals(other);
return field1 == other.field1 && Objects.equals(field2, other.field2) && ...;