Tuesday, April 23, 2013

What will happen if we don’t override the hashcode method?



  • What will happen if we don’t override the hashcode method?


If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.
It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.

JVM assigns unique hashcode value to each object when they are created in memory
if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.

equals() method is used to compare objects that they are having same value or not but why should we override the hashcode method ?
The answer to the question is for the hash technique based data structures like HashMap and HashTable.

every object is placed in Hash bucket depending on the hashcode they have
It is not necessary that every different object must have different hashcode
hashcode is used to narrow the search result

When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and
if yes then it checks for the equals() method.
If two objects are same then HashMap will not add that key
instead it will replace the old value by new one.

http://shivasoft.in/blog/java/what-is-the-need-to-override-hashcode-and-equals-method/