Java HashMap: Internal Working, Buckets, TreeBins & LinkedHashMap

HashMap is an implementation of the Map interface that stores associations between unique Keys and Values. It provides near-instantaneous O(1) average time complexity for get() and put() operations.

How HashMap Works Internally (The 4-Step Lifecycle)

  1. 1. Hash Calculation: When calling map.put(key, value), the JVM executes a hash function: int hash = (h = key.hashCode()) ^ (h >>> 16);.
  2. 2. Bucket Index Calculation: The array bucket index is calculated using bitwise AND: index = (n - 1) & hash, where n is array capacity (default 16).
  3. 3. Collision Handling: If two different keys produce the same bucket index (a Hash Collision), elements are chained together as a singly-linked list of Node<K,V> objects.
  4. 4. Java 8 Treeification: If collisions in a single bucket reach 8 nodes and table capacity is ≥ 64, the bucket linked list automatically converts into a balanced Red-Black Tree (TreeBin). This guarantees worst-case lookup improves from O(n) to O(log n)!

Practical Example: Managing User Sessions

import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {
    public static void main(String[] args) {
        HashMap<String, String> userRoles = new HashMap<>();

        // 1. put(K, V) - Insert or overwrite
        userRoles.put("aarav101", "ADMIN");
        userRoles.put("sneha99", "EDITOR");
        userRoles.put("vikram5", "VIEWER");

        // 2. get(K) - O(1) lookup
        System.out.println("Aarav's Role: " + userRoles.get("aarav101")); // ADMIN

        // 3. getOrDefault() - Safe lookup without null checks
        System.out.println("Unknown user: " + userRoles.getOrDefault("guest", "GUEST_ROLE"));

        // 4. Iterating over Map.Entry sets:
        System.out.println("
--- All Users ---");
        for (Map.Entry<String, String> entry : userRoles.entrySet()) {
            System.out.println("User: " + entry.getKey() + " → Role: " + entry.getValue());
        }
    }
}

University Exam Corner (BCA / B.Sc CS)

Exam Question: "Can an object be modified after being used as a key in a HashMap?"

Answer: Dangerous Trap! If you mutate an object that is actively being used as a HashMap key, its hashCode() will change. When you later attempt to retrieve it using map.get(key), the JVM will compute the new hash code, search in the wrong bucket, and fail to find the entry (returning null)! Always use immutable classes (like String or Integer) as HashMap keys!

Next Step

When you need a key-value map whose keys are sorted in strict ascending order, use TreeMap. Proceed to: Java TreeMap & SortedMap →

Frequently Asked Questions (FAQ)

Q1. What is the internal data structure of a HashMap in Java?
Internally, HashMap consists of an array of Node buckets (Node[] table). In Java 8+, when the number of colliding elements in a single bucket exceeds 8 (TREEIFY_THRESHOLD) and table capacity is >= 64, the linked list transforms into a balanced Red-Black Tree (TreeNode), boosting search speed from O(n) to O(log n).
Q2. What is the Load Factor in a HashMap?
The Load Factor (default 0.75) is the threshold metric that determines when the internal bucket array should be doubled in size. With default initial capacity of 16 and load factor 0.75, when the 13th element is inserted (16 * 0.75 = 12), rehashing doubles capacity to 32.
Q3. What is the difference between HashMap and Hashtable in Java?
HashMap is non-synchronized (faster) and permits one null key and multiple null values. Hashtable is a legacy synchronized class (slower) that forbids null keys and null values entirely.

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Java TreeMap →

Sorted key-value maps.

Java HashSet →

Backed by HashMap.

Collections Class →

SynchronizedMap wrapper.

Java Iterators →

Iterating map entry sets.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!