Collections Framework
HashMap
Analyze HashMap internal mechanics, bucket indexing, hash collision treeification, and resizing concurrency hazards.
Interview: Focuses on hashing algorithm, bucket layouts, collision trees (threshold 8), load factors, and resizing thread safety.
A HashMap is a hash table based implementation of the Map interface. It stores data using a bucket array, handling hash collisions through linked lists that treeify into Red-Black trees when thresholds are met.
Hash Indexing
Computes key hashcode, applies a secondary perturbation hash, and maps it to a bucket using a bitwise mask: index = hash & (n - 1).
Treeification
In Java 8+, if a bucket's elements exceed 8 and table capacity is >= 64, the bucket's linked list converts into a balanced Red-Black tree.
Resizing Costs
When size exceeds the load factor threshold (default 75% of capacity), the capacity doubles. This triggers a rehash of all elements.
Internal Bucketing & Java 8 Treeification
HashMap resolves collisions dynamically using a two-stage structure:
- Linked List Stage: Initially, colliding keys are appended to a singly-linked list in the bucket. Lookup takes
O(K)time, whereKis the list size. - Red-Black Tree Stage: If collision chains grow to
8elements, lookup performance is improved fromO(K)linear time toO(log K)logarithmic time by converting the list to a Red-Black tree. - Untreeification: During resizing or deletion, if a bucket's elements drop to
6or fewer, the tree is converted back to a linked list to reduce tree balance overhead.
Common Pitfalls
- Concurrently Mutating HashMap: Modifying a HashMap from multiple threads during resizing, which can cause data loss, infinite loops, or garbage collector loops.
- Poor Hash Distribution: Storing keys with identical or poorly written hashcode methods, which groups all elements into a single bucket and degrades performance to
O(N)orO(log N).
Best Practices
- Estimate initial capacity: Calculate the required capacity as
expectedSize / loadFactor + 1to prevent performance-intensive rehash cycles. - Use immutable keys: Always use immutable objects (like String or Integer) as keys to prevent hashcode modifications.
Interview-Relevant Information
Q1: What is HashMap treeification and when does it occur?
Answer: Treeification is the process of converting a bucket's singly-linked list into a balanced Red-Black tree. This occurs when a bucket contains 8 or more elements and the overall table capacity is at least 64. It improves worst-case lookup performance from O(K) to O(log K).
Q2: Why is HashMap unsafe for concurrent use?
Answer: HashMap is unsynchronized. During resizing operations, concurrent modifications can corrupt the internal bucket references. In older Java versions, this could cause infinite loop conditions. In modern versions, it leads to data corruption or crashes.
Quick Checklist
Can you write the bucket index formula, state the treeification threshold, list the untreeification threshold, and explain the risks of using HashMap in multi-threaded environments? If yes, you understand HashMap.
Use Cases
Building high-performance in-memory key-value lookups for system cache layers.
Exposing mapped configurations in service classes.
Common Mistakes
Using mutable objects as HashMap keys.
Neglecting to pre-size HashMap capacity for large datasets.