Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Can we have the same hash code for two objects? If yes then what is the reason and if no then what is the reason?

user-image
Question added by Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
Date Posted: 2013/08/21

But Sure, it is a bad coding smell that you have objects return the same hashCode value.
This will be disastrous over performance, especially when you have maps of a huge number of entries.
  :)

Daanish Rumani
by Daanish Rumani , Product Manager , Publicis Sapient

Yes we can.
The reason is that having the same hash code does not mean that the objects are equal.
It merely means that the two objects would fall in the same bucket when using data structures such as HashMaps.
HashMaps organise data into multiple buckets with the idea that the data conjecture it contains can be reasonably segregated.
The benefit is faster searching capability.
Hence the choice of the hash function that generates the hash code can greatly affect performance when the HashMap deals with large number of objects.
Your hash function is nothing but the hashCode() method of Object.
You may use the default implementation in the Object class or override it if it does not meet your performance requirments. 
However when overriding hashCode() you should ensure that two equal objects have the same hash code.
Otherwise they may be treated and not equal.

More Questions Like This