Java:Object類的equals()方法 如何編寫一個完美的equals()方法


一  代碼實例:

package freewill.objectequals;  
/** 
* @author freewill 
* @see Core Java page161 
* @desc getClass實現方式,另有instance of實現方式,根據不同場景使用。 
*/  
public class Employee {  
    private String name;  
    private int salary;  
    private String hireDay;  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public int getSalary() {  
        return salary;  
    }  
  
    public void setSalary(int salary) {  
        this.salary = salary;  
    }  
  
    public String getHireDay() {  
        return hireDay;  
    }  
  
    public void setHireDay(String hireDay) {  
        this.hireDay = hireDay;  
    }  
  
    @Override  
    public boolean equals(Object obj) {  
        // a quick test to see if the objects are identical  
        if (this == obj)  
            return true;  
        // must return false if the explicit parameter is null  
        if (obj == null)  
            return false;  
        // if the class don't match,they can't be equal  
        if (getClass() != obj.getClass())  
            return false;  
        // now we know obj is non-null Employee  
        Employee other = (Employee) obj;  
        // test whether the fileds have identical values  
        return name.equals(other.name) && salary == other.salary  
                && hireDay.equals(other.salary);  
    }  
  
}  
Java語言規范要求equals方法具有下面的特性: 
1.自反性:對於任何非空引用x,x.equals(x)應該返回true。 
2.對稱性:對於任何引用x和y,當且僅當y.equals(x)返回true,x.equals(y)也應該返回true。 
3.傳遞性:對於任何引用x、y和z,如果x.equals(y)返回true,y.equals(z)返回true,x.equals(z)也應該返回true。 
4.一致性:如果x和y引用的對象沒有發生變化,反復調用x.equals(y)應該返回同樣的結果。 
5.對於任意非空引用x,x.equals(null)應該返回false。

 

二  如何表寫一個完美的equals()方法的建議:

1 顯式參數命名為otherObject,稍后需要將它轉化成另一個叫做other的變量;

2 檢測this與otherObject是否引用同一個對象;

     if(this==otherObject){

            return true;          

}

3 檢測otherObject是否為null,如果是,則返回false,

if(otherObject==null){

          return false ;

}

4 比較this和otherObject是否屬於同一個類,如果equals的語義在每個子類中有所改變,就是用getClass()方法檢測;

if(getClass()!=otherObject.getClass()){

return false;

}

如果所有的子類有統一的語義,則使用instanceof檢測;

if(!(otherObject isntanceof ClassName)){

return false;

}

5 將otherObject轉換成相應的類類型變量;

ClassName other=(ClassName)otherObject;

6 現在開始對所需要比較的域進行比較,

    (1)使用==比較基本類型域,

     (2)使用equals比較對象域,

如果所有的域都匹配,則返回true,否則返回false。

格式如下:

return field1==other.field1

&&Objects.equals(field2,other.field2)

&&...........;

如果在子類中重新定義了equals,就要在其中包含調用super.equals(other)。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM