重写Object.hashCode()方法总结

定义

散列码(hash code)是根据对象内容导出的一个整型值,用于标识不同的对象;

而Object类中有默认的hashcode()方法,其值是对象的存储地址

自定义对象重写hashcode()

思路:分别调用类的实例域的hashcode()然后相加来得到该类的hashcode

调用null安全的Objects.hash(Object...objects)来得到总的hashcode

举例:Manager(String sex,int bonus)

    @Override
    public int hashCode() {
        return Objects.hash(sex,bonus);
    }

 若是继承了父类Person,则应该加上super.hashcode()

    @Override
    public int hashCode() {
        return Objects.hash(sex,bonus)+super.hashCode();
    }

与equals关联

equals与hashcode的定义必须一致,即equals返回值要跟hashcode返回值一致

举例:x.equals(y)=true -> x.hashcode()=y.hashcode

因此,一旦重写了类的equals方法就应该重写其hashcode()方法

举例:若Manager.equals是当sex相等时返回true

    @Override
    public boolean equals(Object obj) {
        //1.如果引用相同的对象直接返回true
        if(this==obj)return true;
        //2.因为能够调用equals则表明this不为null,所以如果obj为null,直接返回false
        if(obj==null)return false;
        //3.精确要求类型相等
        if(getClass()!=obj.getClass())return false;
        //4.将obj强制类型转换为当前类型
        Manager object=(Manager)obj;
        //5.域一一对比,因为对象如String要使用equals则必须确保它的域参数不为null,所以要采用Objects.equals(field1,field2)来对比
        return  Objects.equals(this.sex,object.sex);
    }

此时hashcode就只需要计算sex的hash值

    @Override
    public int hashCode() {
        return Objects.hash(sex);
    }

数组的hashcode

Arrays.hashcode(type[] array);

猜你喜欢

转载自www.cnblogs.com/ming-szu/p/9158394.html