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.
Saved automatically
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:
- The key's
hashCode()is computed, then spread via an inte al bitwise hash function. - The array index is determined by
(n - 1) & hash, wherenis the bucket table length. - If the bucket is empty, a new Node is placed.
- 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.
Related Questions in Java
Advanced Java Interview Questions and Answers
Advanced level • 841 views
Java Web development interview questions
Advanced level • 663 views
Java Interview questions
Advanced level • 629 views
Java questions for Newbies
Intermediate level • 573 views
Interview questions on EJB
Advanced level • 454 views