Java Interview Questions – contract between equals and hashCode

Question about contract between equals and hashCode is one of the most common question on interviews for Java developers. Let’s see how somebody should answer and what implications this contract has.

First look at this example:

This example can explain a lot. First of all string a and b are not equal, but their hashCode are the same.

That means that contract for equals and hashCode is:

  • when two objects are equal, their hashCode must be the same,
  • when two objects has the same hashCode, they don’t have to be equal.

Follow up questions

  1. Is hashCode implementation that returns constant value correct?

This is correct implementation but should be avoided because using such objects as keys in HashMap gives performance issues.

  1. How does HashMap handle objects with the same hashCode?

HashMap puts those keys to buckets and than it is using equals to find proper key.