美文网首页
equals和hashcode,他们为何必须一起重写?

equals和hashcode,他们为何必须一起重写?

作者: Android刘东 | 来源:发表于2020-12-29 15:52 被阅读0次

1)hashcode方法

HashMap的put函数

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

如不重写hashCode 某个类的对象a 对象b 属性一样而hashCode不一样 ,导致HashMap的key有2个或多个一样的.
案例

 x类未重写hashcode
HashMap<x类,B类> map=new HashMap<>();

2)equals方法

Object类
    public boolean equals(Object obj) {
        return (this == obj);
    }

如不重写 对象a 对象b 属性一样而equals()返回也是false 根据对象地址而对比
3)总结

两个对象相等,hashCode 一定相等
两个对象不等,hashCode 不一定不等
hashCode 相等,两个对象不一定相等
hashCode 不等,两个对象一定不等

相关文章

网友评论

      本文标题:equals和hashcode,他们为何必须一起重写?

      本文链接:https://www.haomeiwen.com/subject/qqafoktx.html