Quick revision
The short answer
With only 6 distinct regions, OrderKey.hashCode() now returns at most 6 values, so millions of keys fall into at most 6 bins no matter how large the table grows. Each lookup must then search a bin of hundreds of thousands of keys, which tree bins speed up only if OrderKey is Comparable; otherwise it approaches a linear scan with an equals call per entry. The fix is to hash all the fields that equals uses again, and to prevent a repeat with a test that checks how many distinct hashes realistic keys produce, a JMH benchmark on the hot path, and records for value keys.
What to remember
In this answer, we saw that returning only region.hashCode() gave millions of keys just 6 hash values, so they filled at most 6 bins regardless of table size. Tree bins could have bounded the cost only if OrderKey were Comparable; without that, lookups approached a linear scan with equals calls. Restoring a hash over every field that equals uses, ideally by making the key a record, fixes it, and a distinct-hash test, a JMH benchmark and record-based keys stop it from coming back.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
With only 6 distinct regions, OrderKey.hashCode() now returns at most 6 values, so millions of keys fall into at most 6 bins no matter how large the table grows. Each lookup must then search a bin of hundreds of thousands of keys, which tree bins speed up only if OrderKey is Comparable; otherwise it approaches a linear scan with an equals call per entry. The fix is to hash all the fields that equals uses again, and to prevent a repeat with a test that checks how many distinct hashes realistic keys produce, a JMH benchmark on the hot path, and records for value keys.
Why this question is asked
This is a classic production regression: nothing throws, every result is correct, tests pass, and yet a path becomes ten times slower after a harmless-looking refactor. Interviewers like it because finding it requires connecting a small code change to HashMap internals, and preventing it requires thinking about tests that measure quality, not just correctness. In this answer, we will recap how HashMap uses hash codes, follow what happens with 6 distinct hashes, see why tree bins do not save us, fix the key, and set up guards so the regression cannot return unnoticed.
1A Quick Recap of Bins and Hash Codes
HashMap keeps an array of bins, also called buckets. For each key, it takes hashCode(), mixes the high bits into the low bits, and uses the low bits to choose a bin. Inside the bin, it finds the exact key by comparing hashes and then calling equals. A lookup is fast only when bins are small, ideally holding zero, one or two entries.
The number of bins grows as the map grows: the table doubles whenever the size passes 75% of its capacity. With 3 million entries, the table has 4,194,304 bins. The design assumes that different keys produce many different hash codes, so they spread across all those bins.
2Following the Regression
After the refactor, the key looks like this.
- get(key) calls key.hashCode()
region.hashCode(), one of 6 values - Pick the binalways one of the same 6 bins
- Bin is a tree with 500,000 keys
- Is OrderKey Comparable?YescompareTo guides the search: about 19 stepsNohashes all equal, search both subtrees
- Without Comparable: equals on a large share of the binapproaches a linear scan
5 steps in order. Play them, or step through them one at a time.
Only the region decides the bin, so the table size makes no difference.
Notice that the code is still correct. Equal keys still have equal hash codes, because equal keys have equal regions. The contract allows this. But a lookup for one order must now find it among about 500,000 keys that share its hash. Growing the table does not help, because every key with the same hash code always lands in the same bin; doubling the table only adds empty bins.
3Why Tree Bins Do Not Save Us
Java 8 added treeification for this kind of crowding: when a bin passes 8 entries and the table has at least 64 bins, the bin becomes a red-black tree. A tree normally orders entries by their hash, so it can go left or right at each node. Here, every entry in the bin has the same hash, so the hash cannot guide the search.
HashMap's next step is to check whether the key class implements Comparable and, if it does, to use compareTo. With a Comparable OrderKey, the tree can still search in about log2(500,000), roughly 19 steps, which is far slower than one comparison but bounded. OrderKey does not implement Comparable, so the tree has nothing to order by. HashMap still builds the tree using a tie-breaker for insertion, but a lookup cannot use that tie-breaker, so when it cannot decide it searches both subtrees. In practice a large part of the bin is visited, with an equals call at each node. That is where the tenfold slowdown comes from, and it gets worse as the number of orders grows.
4The Fix: Hash Every Field That equals Uses
The correct hashCode combines all the fields used by equals. The simplest way to guarantee that is to make OrderKey a record.
If the class cannot become a record, Objects.hash(region, customerId, orderId) or a hand-written 31 * (31 * region.hashCode() + Long.hashCode(customerId)) + Long.hashCode(orderId) works. The point of the original refactor, that region matters most, does not make it the right hash; the hash exists to tell keys apart, and region is the field that tells them apart least.
5Preventing the Regression
Correctness tests never catch this, because the map still returns the right answers. We need tests that measure the quality of the hash and the speed of the hot path.
The first guard is a unit test that builds a sample of realistic keys, ideally from production-shaped data, and checks that the number of distinct hash codes is close to the number of keys.
The second guard is a JMH benchmark, using the Java Microbenchmark Harness, for the lookup-heavy path, run in CI or before releases with a threshold on the result. JMH handles warm-up and JIT effects that make hand-written timing loops unreliable. A tenfold change would stand out immediately.
The third guard is structural: value keys should be records, so equals and hashCode are generated from the same component list and nobody can edit one without the other. An equals-contract test such as EqualsVerifier adds a check that both methods stay consistent, and a code review checklist can flag any hand-written hashCode on a key class.
6Follow-up questions
How would you confirm this diagnosis in production?
A profiler such as async-profiler or Java Flight Recorder would show time spent in HashMap.getNode, TreeNode.find and OrderKey.equals on the hot path. Comparing the commit history around the latency jump would point to the hashCode change. A quick check of distinct hash codes on a heap dump or sample of keys confirms it.
Would ConcurrentHashMap behave differently?
No. It also bins keys by hashCode and also treeifies crowded bins, with the same dependence on Comparable for equal hashes. Any hash-based structure, including HashSet and caches built on these maps, suffers in the same way.
7Conclusion
In this answer, we saw that returning only region.hashCode() gave millions of keys just 6 hash values, so they filled at most 6 bins regardless of table size. Tree bins could have bounded the cost only if OrderKey were Comparable; without that, lookups approached a linear scan with equals calls. Restoring a hash over every field that equals uses, ideally by making the key a record, fixes it, and a distinct-hash test, a JMH benchmark and record-based keys stop it from coming back.
Open with
The hashCode now returns region.hashCode, and there are only six regions, so millions of keys produce at most six distinct hash values. HashMap chooses the bin from the hash, so all keys land in at most six bins, and resizing does not help because equal hashes always go to the same bin; it only adds empty bins.
Then, if they want more
Each bin holds hundreds of thousands of keys. Those bins become trees, but a tree first orders by hash, and here the hashes are all equal. If OrderKey were Comparable, HashMap could fall back to compareTo and get about 19 steps per lookup.
It is not, so a lookup has to search both subtrees and ends up calling equals on a large part of the bin, which is close to a linear scan. That explains the tenfold latency.
The fix is to hash all the fields equals uses, region, customer id and order id, and the cleanest way is to make OrderKey a record.
To prevent a repeat, I would add a test that hashes a realistic sample of keys and asserts the distinct count is close to the sample size, add a JMH benchmark for the hot lookup path with a threshold, and make records the standard for value keys so equals and hashCode cannot drift apart.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- 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.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
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 "After a refactor, OrderKey.hashCode() was changed to return region.hashCode() because...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/3a7512af1a/