DEV Community

Cover image for HashMap - Internal Working
Madhan Kumar
Madhan Kumar

Posted on

HashMap - Internal Working

πŸš€ 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}
    }
}
Enter fullscreen mode Exit fullscreen mode

βœ… 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.

Image description

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)