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);
    }


}

 

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