Sitemap
Vinotech

Vinotech

Member-only story

What happens if hashCode() and equals() are not overridden correctly in HashMap?

4 min readAug 4, 2025

--

If hashCode() and equals() are not overridden correctly in a HashMap, it can lead to unexpected behavior, such as incorrect key lookups, duplicate entries, or failure to retrieve values. Here’s a detailed explanation of the consequences:

1. Role of hashCode() and equals() in HashMap

  • hashCode(): Determines the bucket where a key-value pair is stored in the HashMap. The hash code is used to compute an index for the internal array.
  • equals(): Used to resolve collisions when multiple keys hash to the same bucket. It checks if two keys are logically equal.

For HashMap to work correctly, these methods must follow the contract:

  • If two objects are equal according to equals(), they must have the same hashCode().
  • If two objects have the same hashCode(), they are not necessarily equal (collisions are allowed).

2. Consequences of Incorrect hashCode() Implementation

Inconsistent Hash Codes:

  • If hashCode() returns different values for the same object during different invocations (e.g., due to mutable fields), the HashMap may fail to locate the key during get() or remove() operations. The key might be in one bucket during put() but looked up in a different bucket later.
class Key {
int value…

--

--