博主是大三的在校大學生,學習計算機的路上,有些自己的感悟,寫下來互相討論下,歡迎吐槽。
Object類是Java中所有的類的始祖,equals()是Object類中檢測一個對象是否等於另外一個對象。這個方法將判斷兩個對象是否具有相同引用,如果兩個對象具有相同的引用,那麼這兩個對象一定相等。但是大多數類來說,這種判斷並沒有什麼意義,如果這兩個對象的狀態相等,就認爲這兩個對象是相等的。所以有時候並不是具有相同引用纔是相等。
因此有必要給出一個完美的重寫equals方法的建議:
1.顯示參數命名otherobject,稍後需要把他轉換成另一個叫做other的變量。
2.檢測this與otherobject是否引用同一個對象
if(this==otherobject) return true;
3.檢測otherobject是否爲null,如果是null返回false。
4.比較this與otherobject是否屬於同一個類。如果equals的語義在每個子類的中有所更改,就用getClass檢測
if(this.getClass()!=otherobject.getClass())
return false;
如果所有子類都擁有統一的語義,就使用instanceof檢測
if(!(otherobject instanceof Classname))
return false;
5.將otherobject轉換爲相應的類類型變量:
ClassName other=(ClassName) otherobject
6.對所有的需要進行比較的域開始比較。使用==比較基本類型域,使用equals比較對象域。如果所有的都匹配,就返回true;否則返回false
return filed1==other.filed1
&& Objects.equals(field2,other.filed2)
&& .....;
完整的代碼:public boolean equals(Object otherobject){
if(this==otherobject)
return true;
if(otherobject==null)
return false;
if(getClass()!=otherobject.getClass())
return false;
Person other=(Person)otherobject;
return name.equals(other.name)
&& money==other.money && ...;
}