Methods Common to All Objects


Item 1: Always override hashCode when you override equals

Important Aspects of Equals and hashcode

Contract between hashcode and equals-
Whenver you are overriding equals method you should override hashcode method too.
1.If two objects are equal according to (java.lang.Object) equals method invocation then te corrsponding hascode should be equal.
2.It is not required that if two objects are distict according to (java.lang.Object) equals method invocation then hascode for two objects to be distinct.
however the programmer should remember that keeping distinct hascode for different object improves working of hashtable.

*Sequence of call to hashcode() and equals() methods and performance optimization: *
Call to hashcode generates an unique ID for an object.
IF hashcode is differnt then two objects wouldn’t be same so there is no need to further call equals().
you can keep hashcode same but then FOR ALL OBJECTS RETURNED HASHCODE will be same and equals will be called always ,so no optimization.
use case 1:
All those classes of Collection that begings with hashe.g hashmap,hashset etc …makes the call to hashcode()
hashcode() is used to DETECT the bucket and equals() search the bucket for the RIGHT ELEMENT using equals
suppose all generated hashcodes are equal the map will point to same bucket [disadvantage–so there wouldn’t be even distributiioni of keys]

use case 2: Overriding hashcode and equals
reference : https://www.geeksforgeeks.org/override-equalsobject-hashcode-method/
case a: when you override both hashcode and equals.
if hashcode method overidden with a field of class (not ensured it to be unique)
and equals with all conditions (with compulsory 3 i.e. same object check(using this),null check and different class check (using getclass()))
so since keys are same the values will be hased to same bucked ovverriding the prviosus value

case b:only overriding equals()
the entry will always go into different bucket irrespective of keys are same or ntii since hascode is not overriden then it uses default and generates a unique hash value.

case c:only overriding hascode()
if there is same keys in hashing then since equals is not overriden so the key will not be replaced instead it will be stored in same bucket as a linked list that is internal to hahmap.

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment