java中輸寫equals和hashCode方法

public class Test{
    private String name;
    private int salary;
    private Date hireDay;

    public boolean equals(Object otherObject){
        if(this == otherObject)     //是否引用同一個對象
            return true;
        if(otherObject == null)     
            return false;
        if(getClass() != otherObject.getClass())        //比較是否屬於同一個類
            return false;
        //所有子類都有統一的語義,就用instanceof檢測:
//        if(!(otherObject instanceof ClassName)) return false;
        Test other = (Test) otherObject;
        return Objects.equals(name,other.name) && salary == other.salary && Objects.equals(hireDay,other.hireDay);
        
        //如果在子類中重新定義equals,就要在其中包含調用super.equals(other)
    }

    public int hashCode(){
        return Objects.hash(name,salary,hireDay);
    }


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章