Why is it important to override HashCode() when you override equals()?

Whenever you override equals(), you must also override hashCode(). Why? Because Java collections like HashMap, HashSet, and Hashtable rely on both methods to correctly store and retrieve objects.

🧠 Let’s break it down:

  1. equals() checks if two objects are logically equal.
  2. hashCode() returns an integer (a hash) used to place the object in hash-based collections.

🔗 How they work together:

If two objects are equal according to equals(), they must return the same hashCode(). If they don’t, collections like HashMap won’t be able to find the object because it’ll be placed in the wrong “bucket.”

🧪 Mini Example:

Now if you put a Book into a HashSet and then try to check if it’s in the set with a new but equal Book object, it’ll fail—because the hashCode() of the new object doesn’t match the original.

✅ So, what should you do?

Always override hashCode() when you override equals() to keep this contract intact:

Overriding equals() without hashCode() is like giving someone your name but not your address—they’ll know who you are, but they’ll never be able to find you.

Want a full example using HashSet to see this in action? It’s a classic gotcha moment worth seeing.

Leave a Reply

Your email address will not be published. Required fields are marked *