Saturday

Overriding hashcode() method in Java and why always override hashcode() if overriding equals()?


Any class in java extend Object class by default. Object class has some non final methods: hashCode(), equals(), toString(), clone() and finalize(). Today we will discuss about hashCode() and equals() method.
  • You you want to use your object in a HashMap, Hashtable,… you need to override hashCode(). “hashCode()” method is supposed to return an int  that should uniquely identify different objects. The default hashCode() return machine address. When we use your object as a key in HashMap/Hashtable, then hashCode of this key will decide where corresponding value is stored in Hash. So if we override hashCode method, then performance of get value from Hash will be increased.

  • If you implemented equals() method, then you have to implement hashCode() method because of simple reason that there’s a consistent with equality: if x.equals(y), then x.hasCode() must == y.hashCode(). 

0 comments:

Post a Comment