加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在什么条件下两个不同的对象可能具有相同的hashcode()值

发布时间:2020-12-15 04:28:37 所属栏目:Java 来源:网络整理
导读:我所知道的是: – “int hashCode()返回对象的内存地址 对象的默认哈希值.“ 如果引用x和y表示两个不同的对象,则表达式 (x.hashCode()== y.hashCode())并不总是false 所以,我想询问在哪些情况下,2个不同对象的哈希值是相同的. 解决方法 您可以在类中重写has
我所知道的是: –

“int hashCode()返回对象的内存地址
对象的默认哈希值.“

如果引用x和y表示两个不同的对象,则表达式
(x.hashCode()== y.hashCode())并不总是false

所以,我想询问在哪些情况下,2个不同对象的哈希值是相同的.

解决方法

您可以在类中重写hashCode.您通常会覆盖它以及重写的等号,因此如果a.equals(b)为真,则a.hashCode()== b.hashCode()也为真(即使(a == b)为false).

但是,即使a.equals(b)为false,a.hashCode()== b.hashCode()仍可能为真.

正如您在Javadoc of Object类中看到的:

  • If two objects are equal according to the equals(Object) method,then calling the hashCode method on each of the two objects must
    produce the same integer result.
  • It is not required that if two objects are unequal according to the java.lang.Object.equals(java.lang.Object) method,then calling the hashCode method on each of the two objects must produce distinct integer results. However,the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读