🚀 How HashMap Works Internally in Java? 🧐
A HashMap in Java is a key-value pair data structure that allows fast retrieval, insertion, and deletion. It is widely used because of its O(1) average time complexity for operations. Let’s break it down in a simple way.
Key Concepts of HashMap:
- Stores data as key-value pairs 🗂️ (key -> value)
- Uses Hashing to find data quickly ⚡
- Allows one null key and multiple null values 🤔
- Does NOT maintain order (Unlike LinkedHashMap) 🔀
- Handles collisions using Linked Lists or Trees 🌳
🔍 How HashMap Works Internally?
When you put a key-value pair in a HashMap, Java follows these steps:
- Calculate the hash of the key using hashCode(). 🔢
- Find the bucket (index) using (hashCode % table size). 🗄️
- Store the key-value pair in the bucket. ✅
- If two keys have the same hash (collision), store them in a linked list (before Java 8) or a balanced tree (after Java 8). 🌲
Example:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
map.put(1, "Avocado"); // Replaces "Apple" because keys are unique!
System.out.println(map); // Output: {1=Avocado, 2=Banana, 3=Cherry}
}
}
✅ Only one value per key..!!! If a key already exists, the old value is replaced.
🔥 Visualization of HashMap Storage:
Imagine buckets where HashMap stores elements.
If you insert another "1 -> Avocado", it replaces "1 -> Apple" because keys must be unique.
🚀 How Does HashMap Handle Collisions?
Sometimes, different keys can generate the same hash (hash collision). Java handles this in two ways:
- Before Java 8 → Uses a Linked List
- Java 8 and later → Uses a Balanced Tree (Red-Black Tree) when collisions become high (threshold = 8).
🔥 Summary
- HashMap stores key-value pairs and finds them fast using hashing.
- Uses hashCode() to compute an index (bucket).
- Handles collisions using Linked List (before Java 8) or Tree (after Java 8).
- Keys must be unique; if a key exists, its value is replaced.