码迷,mamicode.com
首页 > 编程语言 > 详细

Relationship between hashCode and equals method in Java

时间:2019-03-17 13:59:44      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:data   hat   ogr   between   define   java   efi   cat   ola   

转自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

标签:data   hat   ogr   between   define   java   efi   cat   ola   

原文地址:https://www.cnblogs.com/rySZ/p/10546211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!