Test of equality (equals and hash code method)

前端 未结 6 1503
挽巷
挽巷 2021-01-24 21:59

As per the below link

Hashcode and equals

So it is assumed that if 2 objects are equal (that is, equals() returns true), then their hashCodes() must retu

6条回答
  •  离开以前
    2021-01-24 22:47

    Some implementations (for instance HashMap) depend on the fact that when two instances are equal their hashcode should be the same. However, purely using equals will not check hashcodes for those instances.

    In the case of a hashmap, elemets are first divided into different hash buckets based on the hashcodes of objects (for performance reasons). Inside a bucket, equals is used to check object equality. If two equal instances don't have the same hashCode they will end up in different buckets and that might result in unexpected behaviour due to the contract violation.

提交回复
热议问题