Curious Minds

Clear answers to science and history questions

How a HashMap Works in Java

· 6 min read · Science

A HashMap in Java stores key-value pairs in an array of buckets and uses the key's hashCode() to pick a bucket, then equals() to find the exact entry within that bucket. This gives average constant-time O(1) performance for get and put operations, though collisions and resizing can degrade it to O(n) in the worst case.

Background: Why HashMaps Exist

Before hash-based collections, finding an item in a list meant scanning every element—O(n) time. A HashMap trades memory for speed by computing an integer hash from the key and using that number as an index into an internal array. The result is that most lookups touch only one or two array slots, regardless of how many entries the map holds. Java's HashMap, part of the java.util package since Java 1.2, implements the Map interface and permits one null key and multiple null values. It is not synchronized, so it is fast for single-threaded use but unsafe for concurrent modification without external synchronization.

How It Works: The Core Mechanics

Internally, a HashMap is an array of Node objects (called a table). Each Node holds a hash, a key, a value, and a reference to the next node in the same bucket. The process for a put operation follows these steps:

  1. Compute the key's hash code using the key's hashCode() method.
  2. Apply a supplemental hash function (spreading higher bits downward) to reduce collisions.
  3. Compute the bucket index as (n - 1) & hash, where n is the current table length (a power of two).
  4. If the bucket is empty, place the new node there.
  5. If the bucket already contains nodes, traverse the chain (or tree) and compare keys using equals(). If a matching key is found, replace its value. Otherwise, append the new node.

For a get operation, the same hash and index calculation locates the bucket, then equals() identifies the matching key. This is why keys must implement both hashCode() and equals() consistently: if two keys are equal according to equals(), they must return the same hash code.

Collisions and Treeification

When two different keys hash to the same bucket index, a collision occurs. Early Java versions stored colliding entries in a linked list, so lookup time in that bucket grew linearly with the number of collisions. Since Java 8, HashMap converts a bucket's linked list into a red-black tree once the chain length reaches a threshold (TREEIFY_THRESHOLD, default 8) and the table size is at least 64. Tree nodes allow O(log n) lookup within that bucket instead of O(n). If the table is smaller than 64, the map resizes instead of treeifying. When entries are removed and the tree shrinks below UNTREEIFY_THRESHOLD (default 6), it reverts to a linked list.

Resizing and Load Factor

A HashMap has a capacity (the number of buckets) and a load factor (default 0.75). The threshold is capacity × load factor. When the number of entries exceeds this threshold, the map doubles its capacity and rehashes all existing entries into the new table. Rehashing is expensive—O(n)—but happens infrequently enough that amortized cost per insertion remains O(1). Choosing a higher load factor saves memory but increases collision probability; a lower load factor speeds up lookups at the cost of more memory. The default 0.75 is a compromise between time and space.

Choosing Keys and Initial Capacity

Keys should be immutable and have well-distributed hashCode() implementations. Mutable keys are dangerous: if a key's hash code changes after insertion, the entry becomes effectively lost because its bucket index no longer matches. Strings and boxed primitives are common choices because they are immutable and have good hash functions. When you know the expected number of entries in advance, set the initial capacity to avoid repeated resizing. A common rule is to divide the expected size by the load factor and round up to the next power of two—for example, for 100 entries with default load factor, use an initial capacity of 256 (since 100 / 0.75 ≈ 134, next power of two is 256).

Common Problems and Misconceptions

A frequent misconception is that HashMap maintains insertion order. It does not—iteration order is unpredictable and can change after resizing. Use LinkedHashMap if you need predictable iteration order, or TreeMap for sorted keys. Another common issue is using a class that overrides equals() but not hashCode(), or vice versa. This breaks the contract and causes duplicate keys or failed lookups. Also, HashMap is not thread-safe: concurrent puts can cause data loss or infinite loops in older Java versions (though Java 8+ improved this). For concurrent use, use ConcurrentHashMap, which offers better performance than wrapping a HashMap with Collections.synchronizedMap().

HashMap vs. Other Map Implementations

HashMap is the general-purpose choice for unsorted key-value storage. LinkedHashMap extends HashMap and maintains a doubly linked list of entries to preserve insertion order (or access order if configured), at a small memory and performance cost. TreeMap implements a red-black tree and keeps keys sorted according to their natural ordering or a Comparator, with O(log n) operations. Hashtable is a legacy synchronized class that is largely obsolete; ConcurrentHashMap is preferred for concurrency. IdentityHashMap uses reference equality (==) instead of equals() and is suitable only for specific use cases like topology-preserving object graph transformations.

Performance and Cost Considerations

HashMap operations are O(1) on average, but worst-case O(n) if many keys collide (or O(log n) with treeified buckets). The constant factors are low: a get involves one array access, a hash computation, and a short chain traversal. Memory overhead per entry includes the Node object (roughly 32 bytes on a 64-bit JVM with compressed oops) plus the array slot. For very large maps, this overhead can be significant. Iteration over a HashMap takes time proportional to capacity plus size, not just size, because it scans the entire table array. This is why setting a reasonable initial capacity matters for iteration-heavy workloads.

Frequently Asked Questions

Can a HashMap have a null key?

Yes, HashMap permits one null key. It is stored in bucket 0 because the hash of null is defined as 0. Null values are also allowed, and multiple keys can map to null.

Why is the default load factor 0.75?

It balances time and space: a higher factor reduces memory but increases collisions; a lower factor does the opposite. 0.75 is a widely used compromise in hash table implementations.

What happens if two keys have the same hashCode but are not equal?

They end up in the same bucket and are stored in a linked list (or tree). The map uses equals() to distinguish them, so both entries are retained.

Is HashMap thread-safe?

No. Concurrent modification without synchronization can lead to data corruption or exceptions. Use ConcurrentHashMap for multi-threaded access.

How does HashMap handle resizing?

When size exceeds capacity × load factor, the capacity doubles and all entries are rehashed into the new table. This is an O(n) operation but amortized over many insertions.

Can I use a custom object as a key?

Yes, provided the class correctly overrides equals() and hashCode(), and the object is not mutated in a way that changes its hash code after insertion.

In this article
  1. Background: Why HashMaps Exist
  2. How It Works: The Core Mechanics
  3. Collisions and Treeification
  4. Resizing and Load Factor
  5. Choosing Keys and Initial Capacity
  6. Common Problems and Misconceptions
  7. HashMap vs. Other Map Implementations
  8. Performance and Cost Considerations
  9. Frequently Asked Questions