Skip to the page

Collections and generics · core

How HashMap works inside

A HashMap is an array of buckets. The key's hash picks the bucket, equals finds the key, and long buckets turn into trees. It is not thread-safe.

The notes

What you must know

  • An array of buckets; each bucket holds nodes with hash, key, value and next. Default capacity 16, load factor 0.75. When size passes capacity times 0.75, the table doubles.
  • put: hashCode() is spread (h ^ (h >>> 16)), then index = (n - 1) & hash. Capacity is a power of two. Same key found by equals: value replaced.
  • Java 8: a bucket with more than 8 nodes becomes a red-black tree, but only when the table has at least 64 buckets. Otherwise the table resizes.
  • Java 8 resize splits each bucket into "stays at i" or "moves to i + old capacity". Java 7 head insertion could create loops under concurrent resize.
  • One null key is allowed (bucket 0), and null values too.
  • Pre-size to avoid repeated rehashing: HashMap.newHashMap(1_000_000) (Java 19+).
  • Not thread-safe: lost updates and broken internal state with concurrent writes. Iteration order is not defined; LinkedHashMap keeps insertion order.
  • A key with a bad hashCode or a missing equals breaks lookups. See the equals and hashCode topic.

The red pen

Common traps: mistake → fix

  • Mistake: HashMap keeps insertion order

    Fix: order is not defined; use LinkedHashMap.

  • Mistake: A long bucket is always a tree

    Fix: only above 8 nodes and with a table of at least 64 buckets.

  • Mistake: HashMap is safe if threads only read after writes finish

    Fix: without safe publication it is still unsafe; use ConcurrentHashMap for shared writes.

Easy to hard

Questions interviewers ask, easy to hard

  1. Explain how HashMap works inside.
  2. What happens during put?
  3. What changed in Java 8?
  4. Why is HashMap not thread-safe?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview