Understanding equals and hashcode in Java

In Java, Object class has two identity methods called equals and hashcode. We usually override them in our classes to achieve equality. Understanding the underlying mechanism of equals and hashcode can be crucial in some cases. Let’s take a brief look at what they are used for.

  • equals : compares two objects in order to determine if they are equal or not. If you do not override this method or no parent class overrides it, equals method acts like == operator by default. (Beware that == operator compares object references not values.)
  • hashcode: provides and an int value which is derived from the memory address of the object. If two objects occupy same memory address they have same hashcode by default.

If you leave equals and hashcode methods as it is, one can conclude that whenever equals is true for two object, their hashcode value must be same.

So in order to not to break this rule, if you override one of these methods, you must override both.

We have equals, why do we need hashcode ?