π 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.
Top comments (0)