Verified Jobs Live
Java Intermediate Level ~4 min read

What is the internal working of HashMap in Java and how does collision resolution work in Java 8?

Quick Revision Summary

HashMap uses bucket array with hashing. Java 8 improves worst-case collision lookup from O(n) to O(log n) using Red-Black trees when bucket size exceeds 8.

Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Model Answer & Deep-Dive Explanation

In Java, a HashMap works on the principle of hashing. It inte ally uses an array of Node<K,V> buckets. When put(key, value) is called:

  1. The key's hashCode() is computed, then spread via an inte al bitwise hash function.
  2. The array index is determined by (n - 1) & hash, where n is the bucket table length.
  3. If the bucket is empty, a new Node is placed.
  4. If collision occurs (multiple keys map to the same bucket), Java resolves it via linked list chaining.

Java 8 Optimization: When the number of nodes in a bucket exceeds TREEIFY_THRESHOLD = 8 and table capacity is at least 64, the linked list is converted into a Red-Black Tree. This changes worst-case lookup from O(n) to O(log n).

Interviewer Evaluation Points & Scoring Rubric

  • 1 1. Explains bucket index calculation (n-1 & hash). 2. Mentions chaining collision resolution. 3. Highlights Java 8 Red-Black tree threshold (8) and O(log n) complexity.