HashMap Collision Handling and Resizing Techniques

🔍 HashMap Under the Hood When working with HashMaps, collisions are normal. What matters is how we handle them and when we resize the map. 🔹 Collision Handling Techniques 1️⃣ Chaining If two keys map to same index, we store multiple elements at that index using a LinkedList. Example: 12, 17, 22 → all hash to index 2 Index 2 → 12 → 17 → 22 Simple and commonly used. 2️⃣ Open Addressing If index is full, find another empty slot. Linear Probing: Check next index sequentially. Index 2 full → check 3 → check 4 → insert Quadratic Probing: Check using square jumps. Index 2 → 2+1²=3 → 2+2²=6 → 2+3²=11 Reduces clustering compared to linear probing. 3️⃣ Double Hashing Use a second hash function to find a new index. Formula: newIndex = (hash1 + i × hash2) % tableSize This gives better distribution and very less clustering. 🔹 What is Resizing (Rehashing)? When HashMap becomes too full, performance drops. So HashMap increases its size and rehashes all elements again. Condition: Resize when elements > capacity × load factor In Java HashMap: capacity = 16 load factor = 0.75 Resize when elements > 12 Resizing Steps: 1. Create new bigger array 2. Recalculate hash for all elements 3. Insert again into new array Rehashing is expensive but happens rarely. 💡 Easy Summary Chaining → LinkedList at same index Linear Probing → Next index Quadratic Probing → Square jump Double Hashing → Second hash function Resizing → Increase table size & rehash 👉 If you are preparing for Java backend interviews,  connect & follow - I share short, practical backend concepts regularly. #Java #HashMap #DSA #BackendDevelopment #SystemDesign #Programming

  • logo, company name

To view or add a comment, sign in

Explore content categories