Java.Collections.Is it possible for HashMap to degenerate into a list even with keys having different hashCode()?

Yes, a HashMap can degenerate into a linked list even if the keys have different hashCode() values, under certain conditions. Let me explain how and why.

🔍 How HashMap organizes entries:

  1. Each key’s hashCode() is used to determine its bucket index via this internal hash function:

Even if two keys have different hashCode() values, their hashed indices may still collide if:

  • They map to the same bucket index due to modulo with the table size.
  • The internal hash function doesn’t spread them out well enough.
int tableSize = 16;
int hash1 = 0b00010000; // 16
int hash2 = 0b00110000; // 48
// Both (hash & (tableSize - 1)) = 0

➡️ Both keys, despite different hashCode()s, can end up in the same bucket.

🧨 So when does it degenerate into a list?

If:

  • Several such keys hash to the same bucket index.
  • They don’t exceed the threshold (default: 8) for treeification.
  • Or the table size is too small (less than 64), in which case even with ≥8 collisions, Java will not convert it into a tree, to avoid the overhead of tree creation on small maps.

Then the bucket stays a linked list → lookup becomes O(n) in that bucket.


🧠 TL;DR:

  • ✔️ Keys with different hashCode()s can still land in the same bucket.
  • ✔️ This leads to a linked list chain unless treeification occurs.
  • ❌ Treeification requires both:
    • ≥8 nodes in a bucket,
    • Table size ≥64.
This entry was posted in Без рубрики. Bookmark the permalink.