java hashcode与equals,Java中hashCode与equals方法的关系

当在Java中重写equals方法时,通常也需要重写hashCode方法,以保持两个相等对象的hashCode一致性。不这样做可能会导致问题,特别是在使用依赖hashCode的集合如HashMap中。如果两个对象equals相等但hashCode不同,会导致集合行为异常。不违反此约定,在某些特定场景下可能不会立即出现问题,但在多线程或复杂数据结构中可能会遇到不可预测的结果。
摘要由CSDN通过智能技术生成

I read in many places saying while override equals method in Java, should override hashCode method too, otherwise it is "violating the contract".

But so far I haven't faced any problem if I override only equals method, but not hashCode method.

What is the contract? And why am I not facing any problem when I am violating the contract? In which case will I face a problem if I haven't overridden the hashCode method?

解决方案

The problem you will have is with collections where unicity of elements is calculated according to both .equals() and .hashCode(), for instance keys in a HashMap.

As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode().

If you have two objects which are .equals(), but have different hash codes, you lose!

The part of the contract here which is important is: objects which are .equals() MUST have the same .hashCode().

This is all documented in the javadoc for Object. And Joshua Bloch says you must do it in

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值