Relationship between hashCode and equals method in Java

Posted rysz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Relationship between hashCode and equals method in Java相关的知识,希望对你有一定的参考价值。

转自stackoverflow:

Q:

I read in many places saying while override equals method in Java, should override hashCodemethod 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?

 

A:

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().

 

According to the doc, the default implementation of hashCode will return some integer that differ for every object

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation
technique is not required by the JavaTM programming language.)

However some time you want the hash code to be the same for different object that have the same meaning. For example

This kind of problem will be occur if you use a hash data structure in the collection framework such as HashTable, HashSet. Especially with collection such as HashSet you will end up having duplicate element and violate the Set contract.

以上是关于Relationship between hashCode and equals method in Java的主要内容,如果未能解决你的问题,请参考以下文章

The relationship between convergence exponent and upper exponential density

Relationship between frequency and spatial in digital images

Difference between hash() and id()

消息 156,级别 15,状态 1,第 7 行关键字“BETWEEN”附近的语法不正确

[SimHash] find the percentage of similarity between two given data

mysql Hash索引和BTree索引区别