一般重写equals最好重写hashCode方法,并且产生hashCode使用的对象,一定要和equals方法中使用的一致例如equals中用的是employee的id 那么hashCode也用this的id。

如果判断对象相等了,那么他们的hashCode也一定要相等。

但是如果两个相同的类是不同方式得到的,那么他们的hashCode也肯定不相等,所以hashCode最好是返回这个类里面一个属性的值,我这里例子中用的id的hashCode

 

至于hashCode中的17 31 只是一个素数,直接返回this.getId().hashCode();也是可以的。在网上看说是为了避免重复,还不知道为什么...

 

@Override
    public boolean equals(Object object) {
        if(this == object){
            return true;
        }
        if(!(object instanceof Employee)) {
            return false;
        }
        Employee employee= (Employee)object;
        if(this.getId().equals(employee.getId())){
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        //这个类的hashcode其实就是这个类的id*31*17的hashcode
        int  result = 17;
        result = 31 * result + this.getId().hashCode();
        return result;
    }