HashMap in Java

HashMap is Java's fastest general-purpose Map, offering O(1) average get and put via a hash table with linked-list and tree-based collision handling.

HashMap<K, V> is the most widely used Map implementation in Java. It stores key-value pairs in a hash table, providing O(1) average-case time for put, get, and remove. It permits one null key and multiple null values, makes no guarantee about iteration order, and is not thread-safe. Because it shows up in virtually every Java interview, understanding its internal mechanics is essential.

How HashMap Works Internally

Hash table structure

HashMap maintains an array of buckets (default initial capacity: 16). When you call put(key, value):

  1. Java calls key.hashCode() and then applies a secondary spread hash to distribute entries more evenly.
  2. The spread hash is reduced to an array index: index = hash & (capacity - 1).
  3. If the bucket is empty, the entry is inserted directly.
  4. If the bucket already contains entries (a collision), the new entry is appended to a singly-linked list in that bucket.

Treeification

From Java 8, when a single bucket accumulates more than 8 entries and the table capacity is at least 64, the linked list is converted to a balanced red-black tree. This caps worst-case lookup in a heavily-loaded bucket at O(log n) instead of O(n). The tree is converted back to a linked list when the count drops below 6.

Resizing

When the number of entries exceeds capacity × loadFactor (default 0.75), the table doubles in capacity and all entries are rehashed. Resizing is O(n) and can be avoided by pre-sizing: new HashMap<>(expectedSize / 0.75 + 1).

Operation Average Worst case (post-treeification)
put O(1) O(log n)
get O(1) O(log n)
remove O(1) O(log n)
Iteration O(n + capacity) O(n + capacity)

Key characteristics:

  • One null key is allowed; multiple null values are allowed.
  • Iteration order is undefined and may change after resize.
  • Not thread-safe.

Examples

Basic operations

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

public class HashMapBasics {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 90);
        scores.put("Bob", 85);
        scores.put("Alice", 95); // replaces 90; returns old value 90

        System.out.println(scores.get("Alice"));           // 95
        System.out.println(scores.get("Carol"));           // null
        System.out.println(scores.getOrDefault("Carol", 0)); // 0
        System.out.println(scores.containsKey("Bob"));     // true
        System.out.println(scores.size());                 // 2

        scores.remove("Bob");
        System.out.println(scores.containsKey("Bob")); // false

        // Iterate entries (order not guaranteed)
        scores.forEach((name, score) ->
            System.out.println(name + ": " + score));
    }
}

Word frequency counter using merge

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

public class WordFrequency {
    public static void main(String[] args) {
        String[] words = {"the", "quick", "brown", "fox", "the", "quick", "the"};
        Map<String, Integer> freq = new HashMap<>();

        for (String word : words) {
            freq.merge(word, 1, Integer::sum);
        }

        // Sort by frequency descending before printing
        freq.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
            .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
        // the: 3
        // quick: 2
        // brown: 1
        // fox: 1
    }
}

Common Mistakes

  1. Mutable keys. If a key's hashCode or equals changes after it is inserted (because the object is mutable), the entry is stored in the wrong bucket. Subsequent get calls return null even though the key is in the map. Use immutable types — String, Integer, records — as keys.

  2. Missing equals and hashCode. Custom objects used as keys that do not override both methods use reference identity. Two logically equal objects hash to different buckets, so get with a newly created equal object returns null. Use Objects.hash(field1, field2, ...) and a correct equals override.

  3. ConcurrentModificationException. Modifying the map while iterating over its entrySet(), keySet(), or values() throws ConcurrentModificationException. Use iterator.remove(), map.entrySet().removeIf(...), or collect changes outside the loop.

  4. Checking get result for null to infer absence. A key may be present with value null. map.get(k) == null is ambiguous — use map.containsKey(k) to reliably check presence.

  5. Compound check-then-act. if (!map.containsKey(k)) { map.put(k, compute(k)); } is two operations and can be a race condition in concurrent contexts. Use computeIfAbsent(k, fn) instead — it is a single atomic operation in ConcurrentHashMap and cleaner in HashMap too.

Best Practices

  • Declare variables as Map<K, V>, not HashMap<K, V>, for flexibility.
  • Use computeIfAbsent, merge, and getOrDefault instead of manual null checks with get.
  • Pre-size: new HashMap<>(expectedEntries * 4 / 3 + 1) prevents resize operations.
  • Keep keys immutable; if a mutable key is unavoidable, do not change the fields used by hashCode/equals while it is in the map.
  • For multithreaded access, use ConcurrentHashMap rather than synchronizing a HashMap.

Interview Questions

1. How does HashMap work internally?

HashMap stores entries in an array of buckets. The bucket index is derived from the key's hash code spread across the array size. Collisions are stored as a linked list (converted to a red-black tree once a bucket has more than 8 entries and the table has at least 64 slots). The table doubles in size when size > capacity × 0.75.

2. What happens during a hash collision?

When two keys hash to the same bucket, their entries form a linked list in that bucket. get walks the list, calling equals on each entry's key to find the target. From Java 8, buckets with more than 8 entries (in a table of ≥ 64) are treeified to cap worst-case lookup at O(log n).

3. What is the default load factor and why 0.75?

The default load factor is 0.75. It is a balance between time and space: a lower load factor means fewer collisions but more wasted space; a higher load factor saves space but increases collisions. The value 0.75 was chosen empirically as a good trade-off for general-purpose use.

4. Why must equals and hashCode be consistent?

HashMap first identifies a bucket via hashCode (O(1)), then confirms the key with equals (O(1) per comparison in a bucket). If hashCode is inconsistent with equals, two equal objects may be placed in different buckets, and get with one of them will not find the entry stored under the other.

5. Can HashMap store null keys or values?

Yes. HashMap permits one null key (stored in bucket 0) and any number of null values. Hashtable and ConcurrentHashMap do not permit null keys or values.

6. How is HashMap different from Hashtable?

Hashtable is a legacy class (since Java 1.0) that synchronizes every method, making it slower and not recommended for new code. HashMap is unsynchronized, faster, and permits null keys/values. For thread safety, prefer ConcurrentHashMap.

7. How does HashMap behave in a multi-threaded environment?

HashMap is not thread-safe. Concurrent modifications can corrupt the internal structure, and in pre-Java 8 implementations, concurrent rehashing could create infinite loops. Use ConcurrentHashMap for safe concurrent access, or wrap with Collections.synchronizedMap for simple coarse-grained locking.

Summary

  • HashMap uses a hash table with linked-list buckets (treeified at 8 entries / table size ≥ 64) for O(1) average operations.
  • The table resizes at 0.75 load factor; pre-sizing prevents costly rehashing.
  • Keys must be immutable and must correctly implement equals and hashCode.
  • null keys and values are permitted; iteration order is undefined.
  • Not thread-safe — use ConcurrentHashMap for concurrent scenarios.

Continue Learning

Previous: Map | Next: LinkedHashMap

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.