HashMap in Java

Learn how Java HashMap handles keys, collisions, resizing, and iteration, with expected performance, concurrency limits, and JDK-specific internals.

published: reading time: 15 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn how Java HashMap handles keys, collisions, resizing, and iteration, with expected performance, concurrency limits, and JDK-specific internals.

HashMap in Java

HashMap maps keys to values. It uses each key’s hashCode() to select a bucket and equals() to distinguish keys that land there. The API’s constant-time expectation for get() and put() assumes hashes distribute keys properly; collisions add comparison work.

Introduction

HashMap suits key-based access. Keep fields used by a key’s hashCode() and equals() stable while the key is in the map; changing them can make the entry unreachable until the values are restored. The map is unsynchronized. If multiple threads access it and any thread structurally modifies it, synchronize access externally or use a concurrent map. Growth also rebuilds the table, so a resize can add latency during insertion.

This post covers bucket lookup, collisions, resizing, key stability, and what fail-fast iteration does and does not guarantee.

When to Use HashMap

Use HashMap when:

  • You need to store and retrieve values by a unique key
  • Expected constant-time lookup is useful, and keys have a well-distributed hashCode()
  • Keys are not ordered (if ordering matters, use TreeMap or LinkedHashMap)
  • You need a mutable map; for immutable snapshots, consider Map.of() or Collections.unmodifiableMap()

Do not use HashMap when:

  • You need sorted or insertion-order iteration (use TreeMap or LinkedHashMap)
  • You need thread-safe operations (use ConcurrentHashMap)
  • You need null keys in a concurrent map (ConcurrentHashMap does not allow them)
  • You need primitive-key maps without boxing (use Trove or other specialized libraries)

Internal Structure

The Java SE API specifies HashMap behavior, not a particular bucket layout. In OpenJDK 27u, a table contains Node<K,V> buckets; nodes in a bucket form a list until an implementation-specific treeification condition is met. These thresholds are OpenJDK 27u details, not API guarantees:

// OpenJDK 27u implementation details
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;

OpenJDK 27u attempts to treeify a long bucket at the threshold when the table capacity is at least 64. If the table is smaller, it resizes instead. During a resize, a tree bin that splits into a small bin may be converted back to a list at the untreeification threshold.

Mermaid Diagram: HashMap Structure

graph TD
    A["HashMap<K,V>"] --> B["table: Node[16]"]
    B --> C["bucket[0] → Node<K,V> → null"]
    B --> D["bucket[1] → Node → Node → null"]
    B --> E["bucket[2] null"]
    B --> F["bucket[3] → tree bin when eligible"]
    D --> D1["hash: 17<br/>key<br/>value<br/>next: Node"]
    D1 --> D2["hash: 17<br/>key<br/>value<br/>next: null"]
    F --> F1["TreeNode<br/>Red-Black tree"]

Hash Collisions

When different keys have the same hash code or map to the same bucket, a collision occurs. The map compares keys within that bucket. A cluster of collisions increases comparison work. OpenJDK 27u can replace long bins with tree bins under the version-specific conditions above; this behavior is not part of the HashMap API contract.

// Simplified collision handling
if (node.next == null) {
    node.next = new Node(hash, key, value, null);
} else {
    // OpenJDK 27u may resize or treeify a long bin, depending on capacity
}

Failure Scenarios

Scenario Cause Result
ConcurrentModificationException A fail-fast iterator detects an external structural change Best-effort diagnostic; not guaranteed or a correctness tool
Performance degradation Many collisions or poorly distributed hash codes More key comparisons and slower operations
OutOfMemoryError Unbounded growth The application runs out of available memory

Trade-Off Table

Aspect HashMap TreeMap LinkedHashMap
Ordering None Sorted by key (Red-Black) Insertion or access order
Get/Put complexity Expected constant time with good hash distribution O(log n) Expected constant time with good hash distribution
null key allowed Yes (one) No Yes (one)
Thread safety None None None
Memory overhead Lower Higher (tree structure) Higher (linked list)

Code Snippets

Basic Operations

HashMap’s everyday API boils down to four operations: put(), get(), remove(), and containsKey(). put() inserts or overwrites a value and returns whatever was previously mapped to that key — useful when you need to know whether you just clobbered something. get() retrieves by key, remove() deletes, and containsKey() checks existence.

getOrDefault() returns the default when the key is absent; get() returns null both for an absent key and a key mapped to null. Use containsKey() when that distinction matters. getOrDefault() is also useful for counting and accumulator patterns.

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

public class HashMapBasicsDemo {
    public static void main(String[] args) {
        Map<String, Integer> ages = new HashMap<>();
        ages.put("Alice", 30);
        ages.put("Bob", 25);
        System.out.println(ages.get("Alice")); // 30
        System.out.println(ages.getOrDefault("Eve", 0)); // 0
        ages.remove("Bob");
        System.out.println(ages.containsKey("Bob")); // false
        System.out.println(ages.size()); // 1
    }
}

Save this as HashMapBasicsDemo.java, then run javac HashMapBasicsDemo.java && java HashMapBasicsDemo:

30
0
false
1

Custom Key with Proper HashCode

If you use a custom object as a HashMap key, you must override both hashCode() and equals(), and both must depend on the same fields. The rule: objects that are equals() must have the same hashCode(). The reverse is not required, but violating the forward direction is the most common cause of “where did my entry go?” bugs.

Fields used by hashCode() and equals() must stay stable while a key is stored in the map. If they change, lookups may miss the entry until those fields are restored. Objects.hash() on stable fields is a common way to implement hashCode() without writing the arithmetic by hand.

A minimal correct implementation looks like this:

class Employee {
    private final int id;
    private final String name;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee that = (Employee) o;
        return id == that.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);  // Use only immutable field(s)
    }
}

Iterating

HashMap gives you three iteration views. Use entrySet() when you need both the key and value — it avoids a separate hash lookup for each key. Use keySet() when you only need the keys, though for bulk access entrySet() is faster. Use values() when you only need the values.

Avoid structurally modifying the map outside its iterator while traversing a collection view. A fail-fast iterator may throw ConcurrentModificationException after such a change, but detection is best-effort and must not be used for correctness. If removal is needed, use the iterator’s supported remove() method. The HashMap API also documents that iterating a view takes time proportional to table capacity plus map size.

for (Map.Entry<String, Integer> entry : ages.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

// KeySet iteration
for (String key : ages.keySet()) { }

// Value iteration
for (Integer val : ages.values()) { }

Observability Checklist

  • Test representative key sets for collision-heavy hashCode() distributions
  • Profile lookup and insertion costs under expected and collision-heavy workloads
  • Log size() over time to detect unbounded map growth
  • Review any ConcurrentModificationException as a bug signal, not a correctness mechanism
  • Treat treeification thresholds as implementation details; the OpenJDK 27u values are documented above

Security Notes

  • HashMap is unsynchronized. If multiple threads access it and any thread structurally modifies it, synchronize externally or use ConcurrentHashMap.
  • A Collections.synchronizedMap() wrapper requires callers to synchronize on the wrapper while iterating its views.
  • When using user-supplied keys, a malicious hashCode() implementation could trigger DoS attacks (hash flooding)
  • Avoid serializing maps containing sensitive data; use encrypted serialization or secure alternatives
  • Map.of() creates an unmodifiable map; Collections.unmodifiableMap() creates an unmodifiable view of its backing map

Common Pitfalls / Anti-Patterns

  1. Mutable keys: If a key’s hashCode() changes after insertion, the entry becomes unretrievable — the map cannot find it
  2. Poor hashCode(): Returning a constant (e.g., return 42) places many keys in the same bucket and increases comparison work, slowing lookups and updates
  3. Confusing put() return value: put() returns the previous value or null; use containsKey() if you need to distinguish no mapping from a previous null value
  4. null key: Only one null key is allowed; subsequent put(null, value) overwrites the first
  5. Ignoring rehashing: Growth rebuilds the table and revisits entries, which can cause an insertion latency spike. Estimate the expected size when constructing a large map.

Quick Recap

  • HashMap documents expected constant-time get() and put() when hashes distribute keys properly
  • Collisions add comparison work; tree bins and thresholds are implementation details
  • Keys must have stable hashCode() and correct equals() implementations
  • null key and null values are supported (single null key)
  • Unsynchronized; synchronize structural writes externally or choose ConcurrentHashMap for concurrent access

Interview Questions

1. What is a hash collision and how does HashMap handle it?
A collision occurs when different keys have the same hash code or map to the same bucket. The map compares keys within that bucket. OpenJDK 27u may treeify a long bin when capacity is at least 64; at smaller capacities it resizes instead. These are implementation details, not API guarantees.
2. What determines the bucket index for a key?
The `HashMap` API does not specify a bucket-index formula. In OpenJDK 27u, the implementation spreads bits from `hashCode()` and masks them with `capacity - 1` for its power-of-two table. That source-level detail can change between implementations or versions.
3. What happens when HashMap needs to resize?
When entries exceed `capacity * loadFactor`, the map rehashes its contents into a larger table. The API describes the new table as having approximately twice as many buckets. A resize must revisit existing mappings, so it can add latency during a write. Estimate the expected size when constructing a large map to reduce growth resizes.
4. Why should custom key objects override both `hashCode()` and `equals()`?
`HashMap` uses `hashCode()` to select a bucket and `equals()` to identify a matching key within it. The contract requires equal objects to have equal hash codes, though equal hash codes do not require equal objects. Override both methods consistently so equal keys behave as one mapping.
5. What is the difference between `HashMap` and `ConcurrentHashMap`?
`HashMap` is unsynchronized. If multiple threads access it and at least one structurally modifies it, synchronize access externally or use a map designed for concurrent access. `ConcurrentHashMap` supports concurrent operations; a `Collections.synchronizedMap()` wrapper is another option, but callers must synchronize on that wrapper while iterating.
6. What is the purpose of the `hash()` method in HashMap?
OpenJDK 27u spreads bits from `hashCode()` before choosing a bucket. The exact method is an implementation detail, and a mixing step cannot repair a hash function that returns the same value for many unequal keys.
7. When does a HashMap bucket convert from linked list to a tree?
In OpenJDK 27u, the treeification threshold is 8, the untreeification threshold during a resize is 6, and the minimum table capacity for treeification is 64. A crowded bin in a smaller table triggers a resize instead of treeification. These values and transitions are implementation details, not `HashMap` API guarantees.
8. What is the difference between `get()` and `getOrDefault()`?
`get(key)` returns `null` both when the key is absent and when it maps to `null`. `getOrDefault(key, defaultValue)` returns the default only when the key is absent. Use `containsKey()` if you need to tell those cases apart.
9. How does HashMap handle hash flooding attacks?
Hash flooding supplies many keys that collide, increasing the comparisons needed for operations. The `HashMap` API does not promise a general defense against attacker-controlled keys. OpenJDK 27u can treeify eligible crowded bins, subject to its 8/6/64 thresholds, but applications should still bound untrusted input and choose a map suited to their threat model.
10. Why is it recommended to use immutable types as HashMap keys?
If fields used by `hashCode()` or `equals()` change while a key is stored, lookups may no longer find it in its original bucket. Immutable key types avoid that problem; for custom keys, keep the relevant fields stable while they are in the map.
11. What is the difference between `putIfAbsent()` and `put()`?
`put()` replaces the current value and returns the previous value, or `null` if there was no non-null previous value. `putIfAbsent()` inserts when the key is absent or currently mapped to `null`. Use `containsKey()` if you must distinguish no mapping from a mapping whose value is `null`.
12. What is the difference between `HashMap` and `Hashtable`?
`Hashtable` is a legacy synchronized implementation that does not allow `null` keys or values. `HashMap` is unsynchronized and allows one `null` key and multiple `null` values. For concurrent access, prefer `ConcurrentHashMap` when its `null` restrictions fit the use case.
13. How does HashMap determine when to resize its bucket array?
The map resizes when its entry count exceeds the current capacity times its load factor. The default load factor is 0.75; the API says rehashing increases the bucket count to approximately twice its prior capacity. A resize revisits existing entries and may cause a write-latency spike.
14. What is the purpose of the `hash()` method in HashMap?
OpenJDK 27u spreads high bits from `hashCode()` into lower bits before selecting a bucket. This implementation detail helps its power-of-two table use more of the hash value; the `HashMap` API does not specify this formula.
15. What is the relationship between HashMap's initial capacity and load factor?
Initial capacity and load factor influence when the map grows. The default load factor is 0.75. If the expected mapping count is known, choose a constructor capacity large enough to reduce intermediate resizes; the exact capacity strategy is an implementation detail.
16. Can two different keys have the same hash code in HashMap?
Yes. `HashMap` uses `hashCode()` to select a bucket and `equals()` to distinguish keys within it. Unequal keys with the same hash can coexist in the same bucket, though many collisions increase comparison work.
17. How does HashMap's `computeIfAbsent()` method work?
`computeIfAbsent(key, mappingFunction)` returns a non-null existing value, or calls the function when the key is absent or mapped to `null`. If the function returns a non-null value, the method stores and returns it. `HashMap` is unsynchronized, so this method does not make concurrent updates safe or provide cross-thread atomicity.
18. What is a HashMap collision and how does it affect performance?
Collisions require additional key comparisons within a bucket, so poor hash distribution slows access. OpenJDK 27u may treeify an eligible crowded bin; its threshold depends on both bin size and table capacity. The API promises expected constant-time basic operations only when hashes distribute keys properly.
19. Why does HashMap use separate chaining and tree structures for collision handling?
A list keeps ordinary bins simple, while a tree can reduce comparisons in a crowded bin. In OpenJDK 27u, treeification uses the 8-entry threshold only when table capacity is at least 64; otherwise the implementation resizes. These are version-specific implementation choices, not universal `HashMap` guarantees.
20. What is the difference between `clear()` and `remove()` in HashMap?
`clear()` removes all entries but keeps the bucket array. `remove(key)` removes one mapping. After `clear()` or many `remove()` calls, `HashMap` does not automatically shrink its table.

Further Reading

Conclusion

HashMap is a key-value store with expected constant-time get() and put() when hashes distribute keys properly. Collisions add comparisons, so key distribution affects observed performance. Keys also need stable hashCode() and consistent equals() behavior while stored.

Immutable keys such as String and Integer avoid key-stability problems. With custom keys, keep fields used by hashCode() and equals() unchanged while the key is stored. HashMap is unordered; use TreeMap for sorted keys or LinkedHashMap when iteration order matters.

HashSet is the set counterpart to HashMap; it uses a map internally to store unique elements. See HashSet in Java for its membership and equality behavior.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals