栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在java中为什么需要覆盖equals和hashcode方法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在java中为什么需要覆盖equals和hashcode方法?

让我们尝试通过一个示例来理解它,如果我们

equals()
不进行覆盖而覆盖
hashCode()
并尝试使用
Map

假设我们有一个类像这样那样的两个对象

MyClass
是相等的,如果他们
importantField
等于(
与hashCode()
equals()Eclipse
生成)

public class MyClass {    private final String importantField;    private final String anotherField;    public MyClass(final String equalField, final String anotherField) {        this.importantField = equalField;        this.anotherField = anotherField;    }    public String getEqualField() {        return importantField;    }    public String getAnotherField() {        return anotherField;    }    @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result     + ((importantField == null) ? 0 : importantField.hashCode());        return result;    }    @Override    public boolean equals(final Object obj) {        if (this == obj) return true;        if (obj == null) return false;        if (getClass() != obj.getClass()) return false;        final MyClass other = (MyClass) obj;        if (importantField == null) { if (other.importantField != null)     return false;        } else if (!importantField.equals(other.importantField)) return false;        return true;    }}

仅覆盖

equals

如果仅

equals
覆盖被覆盖,则在你
myMap.put(first,somevalue)
第一次调用时将散列到某个存储桶,而在调用
myMap.put(second,someOtherValue)
时将散列到其他存储桶(因为它们具有不同的
hashCode
)。因此,尽管它们是相等的,但由于它们没有散列到同一个存储桶中,因此地图无法实现,因此它们都留在了地图中。

尽管

equals()
如果我们要覆盖,则不必覆盖
hashCode()
,但让我们看看在这种特殊情况下会发生什么,在这种情况下,我们知道如果两个对象
MyClass
相等,则它们
importantField
相等但我们不覆盖
equals()

仅覆盖

hashCode

想象你有这个

MyClass first = new MyClass("a","first");MyClass second = new MyClass("a","second");

如果仅覆盖,hashCode则在调用

myMap.put(first,somevalue)
它时会先进行计算,
hashCode
然后将其计算并存储在给定存储桶中。然后,在调用时
myMap.put(second,someOtherValue)
,应根据地图文档将其替换为第二,因为它们相等(根据业务要求)。

但问题是,等于没有重新定义,所以当图哈希second通过桶和迭代,查找是否有一个对象k,从而

second.equals(k)
是事实,就不会找到任何的
second.equals(first)
fals
e。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/369800.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号