Scrivio Interview library
InternalsFoundations7 min read · updated 12 November 2026

Walk through what java.util.HashMap does, from calling hashCode() to choosing a bucket, when you call map.put(key, value) in Java 8 or later.

When we call map.put(key, value), HashMap takes the key's hashCode(), mixes it, and uses the result to pick a bucket in its internal array. In that bucket it either finds an equal key and replaces its value, or adds a new entry. When the map gets too full, it doubles the array and spreads the entries out again.

Why this question is asked

HashMap is one of the classes we use every day without thinking about what happens inside it. Interviewers ask about it because the internals explain real problems we meet in production: maps that get slow, keys that seem to disappear, and memory that grows more than expected. In this answer, we will follow one put() call from start to finish, see why each step exists, and then look at what happens when keys collide and when the map has to grow.

1A Quick Recap of HashMap

A HashMap stores key-value pairs. We give it a key, and it gives back the value stored for that key. Its promise is speed: a lookup should take about the same time whether the map holds ten entries or ten million.

To keep that promise, HashMap never searches through all its entries. Internally it holds an array (it calls it the table), and each slot of that array is called a bucket. A new HashMap starts with 16 buckets. For every key, HashMap calculates which bucket the entry belongs in and goes straight there.

Two methods of the key make this work. hashCode() turns the key into an int, a kind of numeric fingerprint. equals() tells whether two keys are the same key. HashMap uses the first to find the bucket quickly and the second to be sure it found the right key inside that bucket.

2Getting a Hash From the Key

The first thing put() does is call hashCode() on the key. For a String, Java builds this number from its characters.

Java
String key = "cat";
int h = key.hashCode(); // 98262
int hash = h ^ (h >>> 16); // 98263: the top 16 bits are mixed into the bottom 16 bits

Notice that HashMap does not use the hashCode() as it is. It mixes the upper 16 bits into the lower 16 bits. The reason is the next step: choosing a bucket only looks at the lowest few bits of the number. Without this mixing, keys whose hash codes differ only in their high bits would all end up in the same bucket. With it, they spread out.

3Finding the Bucket

Now HashMap turns the hash into a bucket number between 0 and 15. It does this with a bit mask instead of a division.

Java
int n = 16; // number of buckets in a new map
int index = (n - 1) & hash; // 98263 & 15 = 7, so "cat" goes to bucket 7
int withoutMixing = (n - 1) & h; // 98262 & 15 = 6, it would have been bucket 6
Step throughWhat put("cat", 1) does
  1. Call "cat".hashCode()98262
  2. Mix the high bits into the low bits98262 ^ (98262 >>> 16) = 98263
  3. Pick the bucket(16 - 1) & 98263 = 7
  4. Is bucket 7 empty?
    YesStore a new node and finishNoLook for the key in the bucket
  5. Same hash and equals()?
    YesReplace the value, return the old oneNoAdd a new node to the bucket
  6. More than 12 entries now?
    YesDouble the table to 32 bucketsNoDone

6 steps in order. Play them, or step through them one at a time.

The number of buckets is always a power of two (16, 32, 64 and so on). For a power of two, (n - 1) & hash gives the same result as hash % n, the remainder after dividing by n, but it is a single fast bit operation. This is the reason HashMap rounds every capacity up to a power of two. As the last line shows, the mixing from step 1 really changes where an entry lands.

4Putting the Entry Into the Bucket

HashMap goes to bucket 7. If the bucket is empty, it stores a new node there. A node is a small object that holds the hash, the key, the value and a link to the next node in the same bucket.

If the bucket already has nodes, HashMap must find out whether our key is already in the map. For each node, it first compares the stored hash with our hash, then checks whether the keys are the same object, and only then calls equals(). Comparing two ints is almost free, and different hashes mean the keys cannot be equal, so most nodes are ruled out before equals() is ever called.

Java
Map<String, Integer> map = new HashMap<>();
System.out.println(map.put("cat", 1)); // null: a new entry was added
System.out.println(map.put("cat", 2)); // 1: same key, so the old value is replaced and returned
System.out.println(map.size()); // 1

So put() returns the previous value when the key already existed, and null when it added a new entry. That return value is often the quickest way to tell which of the two happened.

5What Happens When Two Keys Land in the Same Bucket?

Two different keys can end up in the same bucket. This is called a collision, and it is normal. It even happens with keys whose hash codes are exactly equal. The strings "Aa" and "BB" are a well-known example.

Java
System.out.println("Aa".hashCode()); // 2112
System.out.println("BB".hashCode()); // 2112
Map<String, String> m = new HashMap<>();
m.put("Aa", "first");
m.put("BB", "second"); // same bucket as "Aa"
System.out.println(m.get("BB")); // second
System.out.println(m.size()); // 2
Buckets of a small map
BucketNodes in itWhy
0"Aa" -> first, "BB" -> secondboth hash to 2112, so equals() tells them apart
2"dog" -> 3one key, found with one comparison
7"cat" -> 2mixed hash 98263 & 15 = 7
other 13emptynothing stored yet
A collision is normal: two nodes share bucket 0 and equals() decides which one we asked for.

Both keys go into the same bucket, one after the other. When we call get("BB"), the hashes match for both nodes, so HashMap calls equals() to tell them apart. This is why equals() matters as much as hashCode(): the hash finds the bucket, and equals() finds the key.

A few nodes in one bucket cost very little. Many nodes would make every lookup in that bucket slow, because HashMap would compare against each of them. So since Java 8, when a single bucket reaches 8 nodes and the table has at least 64 buckets, HashMap turns that bucket into a small red-black tree. Lookups in that bucket then take logarithmic time instead of linear time.

6Resizing the Bucket Array

After each insertion, HashMap checks whether it has become too full. The limit is the capacity times the load factor, which is 0.75 by default. For a new map that is 16 x 0.75 = 12 entries. When the 13th entry arrives, HashMap doubles the table to 32 buckets and places every existing entry into the new table.

Because the size exactly doubles, each entry either keeps its bucket number or moves to its old number plus the old capacity, depending on a single bit of its hash. That keeps the move cheaper than recalculating everything from scratch, but it is still work proportional to the number of entries.

Java
// If we know the map will hold about a million entries, we create it with that size
Map<Long, Order> orders = HashMap.newHashMap(1_000_000); // Java 19 and later; no resizing on the way

Creating the map with the expected size avoids many rounds of resizing when we already know roughly how many entries it will hold.

7When a Missing hashCode() Breaks the Map

Here is the failure that shows why both methods matter. The class below overrides equals() but not hashCode().

Java
class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
return o instanceof Point p && p.x == x && p.y == y;
}
// hashCode() not overridden
}
Map<Point, String> places = new HashMap<>();
places.put(new Point(1, 2), "home");
System.out.println(places.get(new Point(1, 2))); // null (almost always)

The two Point objects are equal, but they inherit Object.hashCode(), which is different for every object. So the second Point is looked up in a different bucket, and HashMap never even gets to call equals(). Adding a hashCode() that combines x and y, or simply declaring Point as a record, fixes it.

8Follow-up questions

Why does HashMap compare the stored hash before calling equals()?

Because it is much cheaper and it rules out almost every wrong node. Comparing two ints is one instruction, while equals() may compare long strings or run code written by the key's author. If the hashes differ, the keys cannot be equal.

Where does HashMap store a null key?

HashMap treats the hash of null as 0, so a null key always goes to bucket 0. HashMap allows one null key. ConcurrentHashMap does not allow null keys or values at all.

Is get() always O(1)?

On average, yes, when keys spread well. In the worst case, when many keys fall into one bucket, a treeified bucket makes it O(log n). Before Java 8, such a bucket was a plain linked list and the worst case was O(n).

9Conclusion

In this answer, we followed a put() call through HashMap. It takes the key's hashCode(), mixes the high bits into the low bits, and picks a bucket with a bit mask because the table size is a power of two. Inside the bucket it checks the stored hash before equals(), replaces the value of an existing key or adds a new node, turns crowded buckets into trees since Java 8, and doubles the table once it passes three quarters full. We also saw why equals() and hashCode() must always be overridden together.

What to say in the interviewAbout 60 seconds aloud

Open with

When I call put, HashMap first calls hashCode on the key and mixes the upper 16 bits into the lower 16 bits, because the bucket is chosen from the low bits only: the index is hash AND table length minus one, which works as a cheap remainder because the length is always a power of two.

Then, if they want more

In the bucket it compares the stored hash first, then reference equality, then equals, to find an existing key. If it finds one, it replaces the value and returns the old one; otherwise it adds a new node.

Since Java 8, a bucket with eight or more nodes in a table of at least 64 buckets becomes a red-black tree, so collisions cannot make lookups linear. Finally, if the size passes capacity times the load factor, 12 for a default map, the table doubles and each entry either stays at its index or moves by the old capacity.

About this answer

Last updated
12 November 2026
Versions it names
Java 8, Java 19
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Walk through what java.util.HashMap does, from calling hashCode() to choosing a bucket...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/6740d02c49/

More in HashMap and map implementations