Quick revision
The short answer
HashMap keeps its table length a power of two so it can pick a bucket with a single bit mask, (n - 1) & hash, instead of a slower integer division, and so that doubling the table moves each entry to either the same index or index + oldCap. The price is that only the low bits of the hash choose the bucket, so HashMap mixes the high 16 bits into the low ones with h ^ (h >>> 16). Prime-sized tables forgive weak hashes better but pay for a modulo on every lookup, and keys whose hashes differ only in a few bits can still cluster badly in a power-of-two table.
What to remember
In this answer, we saw that HashMap uses power-of-two tables so it can index with (n - 1) & hash, which costs one AND instead of a division, never goes negative, and makes resizing a matter of one extra bit: each entry stays at index i or moves to i + oldCap. The trade-off is that only the low bits of the hash pick the bucket, so HashMap folds the high 16 bits into the low ones with h ^ (h >>> 16). Prime-sized tables would forgive weak hashes better at the cost of a modulo per lookup, and keys whose hashes vary only in a few bits, such as multiples of a large power of two, still cluster and end up in tree bins.
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.
HashMap keeps its table length a power of two so it can pick a bucket with a single bit mask, (n - 1) & hash, instead of a slower integer division, and so that doubling the table moves each entry to either the same index or index + oldCap. The price is that only the low bits of the hash choose the bucket, so HashMap mixes the high 16 bits into the low ones with h ^ (h >>> 16). Prime-sized tables forgive weak hashes better but pay for a modulo on every lookup, and keys whose hashes differ only in a few bits can still cluster badly in a power-of-two table.
Why this question is asked
This question goes one level below how HashMap works and asks why it was built that way. It matters in practice because the design decides which hashCode() implementations are good enough and which ones quietly turn a map into a slow list. Interviewers ask it at a senior level to see whether we can reason about trade-offs rather than recite facts. In this answer, we will recap how a bucket index is computed, compare a bit mask with a modulo, see what the power-of-two choice gives resizing, look at the weakness it creates and the spreading step that softens it, and finish with the keys that still cause trouble.
1A Quick Recap: From Hash to Bucket
A HashMap holds an array called the table, and each slot is a bucket. To store a key, the map calls hashCode(), which returns an int, and must turn that int into an index between 0 and n - 1, where n is the table length. The classic textbook way is the remainder, hash % n, with a prime n so the remainder depends on all bits of the hash.
Java's HashMap instead keeps n at 16, 32, 64 and so on, and computes the index as (n - 1) & hash. For a power of two, n - 1 is a run of ones in binary (15 is 1111), so the AND simply keeps the lowest log2(n) bits of the hash. For non-negative numbers that is the same result as hash % n, and it also works for negative hashes, where % would give a negative index.
2Why a Bit Mask Instead of a Modulo
The first reason is speed. An AND is one of the cheapest instructions a CPU has, while integer division takes many cycles, typically tens on common hardware. A HashMap lookup is often only a handful of instructions, so a division on every get() and put() would be a noticeable share of the cost. Compilers can turn % by a constant into multiplications, but the table length changes at runtime, so that trick does not apply.
Notice that the mask never produces a negative index, so the code needs no extra fix-up for negative hash codes, which are common.
3What Powers of Two Give the Resize
The second reason is resizing. When the map grows, it doubles the table from oldCap to 2 * oldCap. The new mask has exactly one more bit than the old one, so for every entry the new index depends only on that one extra bit of its hash, the bit at position oldCap.
So during a resize, Java 8 and later walk each bucket once and split it into a lo list that stays at index i and a hi list that moves to i + oldCap, keeping the original order. There is no need to recompute indexes from scratch. With a prime-sized table, growing to the next prime would scatter every entry to an unrelated position.
4The Weakness: Only the Low Bits Count
The mask throws away every bit above the lowest few. In a table of 16 buckets, only the bottom 4 bits of the hash matter. Two keys whose hash codes differ only in their high bits land in the same bucket every time, however different they look.
A prime modulo does not have this problem in the same way, because the remainder after dividing by a prime depends on every bit of the number. That is why textbooks prefer prime sizes: they forgive a mediocre hash function. Java chose speed and simple resizing and moved the protection elsewhere.
5The Spreading Step That Softens It
Before masking, HashMap.hash() computes h ^ (h >>> 16). That folds the upper 16 bits onto the lower 16, so a difference in the high half of the hash also changes the low bits that the mask keeps.
- key.hashCode()any 32-bit int, maybe weak
- Spread: h ^ (h >>> 16)high half folded into low half
- Mask: (n - 1) & hashkeeps the lowest
log2(n)bits - Bucket ion resize: stays at i or moves to i +
oldCap
4 steps in order. Play them, or step through them one at a time.
The spread step is the price of using a mask instead of a modulo.
The step is deliberately cheap, one shift and one XOR, because it runs on every operation. Earlier JDKs used a heavier mixing function. Java 8 made it lighter because red-black tree bins now cap the damage of collisions, so the hash no longer has to be perfect.
6Keys That Still Cluster Badly
Spreading only mixes 32 bits into 16. If a key class produces hashes that vary in just a few bits overall, nothing can invent the missing variety. Suppose a hashCode() returns id << 26 for sequential ids, that is, id times 2^26. Every such hash has zeros in its lowest 26 bits, and after spreading, the low 4 bits are still zero, so in a table of 16 buckets every key lands in bucket 0. Ids above 63 also overflow the int and start repeating the same few values.
Real examples are hashCode() methods that combine fields with XOR so that equal fields cancel out (x ^ y is 0 whenever x == y), enums or booleans used as the only field, or float bit patterns where only the exponent changes. In a power-of-two table these cluster into a few buckets, those buckets grow long, and once a bucket reaches 8 nodes in a table of at least 64, it becomes a red-black tree, which keeps lookups O(log n) but is still far slower than O(1).
| Aspect | (n - 1) & hash, n = 2^k | hash % p, p prime |
|---|---|---|
| Cost per lookup | one AND | an integer division |
| Negative hashes | always in range | needs Math.floorMod or a fix |
| Resize | entry stays at i or moves to i + oldCap | every entry recomputed |
| Bits that matter | only the low k bits (after spreading) | all bits |
Weak hashCode() | clusters unless spread or treeified | more forgiving |
7Follow-up questions
How does tableSizeFor turn a requested capacity into a power of two?
It returns the smallest power of two that is at least the requested capacity, capped at 2^30. Older code did it with bit smearing: subtract one, then OR the number with itself shifted right by 1, 2, 4, 8 and 16 so every bit below the highest one becomes 1, then add one. Newer JDKs compute the same value as (-1 >>> Integer.numberOfLeadingZeros(cap - 1)) + 1 (check your version for the exact code). So new HashMap<>(1000) gets a table of 1024, and new HashMap<>(1024) also gets 1024 because of the initial subtraction. The table itself is allocated lazily on the first put.
Should we write hashCode() differently because of this?
We should make sure the low bits vary. Combining fields with 31 * h + field, as Objects.hash and records do, spreads changes across the bits well enough. We should avoid plain XOR of fields, shifting values into high bits only, and hashes built from a single low-cardinality field.
Does ConcurrentHashMap use the same scheme?
Yes. It also uses power-of-two tables, a spreading function that folds the high bits down (and clears the sign bit, since negative hashes have special meanings in its nodes), and tree bins for crowded buckets.
8Conclusion
In this answer, we saw that HashMap uses power-of-two tables so it can index with (n - 1) & hash, which costs one AND instead of a division, never goes negative, and makes resizing a matter of one extra bit: each entry stays at index i or moves to i + oldCap. The trade-off is that only the low bits of the hash pick the bucket, so HashMap folds the high 16 bits into the low ones with h ^ (h >>> 16). Prime-sized tables would forgive weak hashes better at the cost of a modulo per lookup, and keys whose hashes vary only in a few bits, such as multiples of a large power of two, still cluster and end up in tree bins.
Open with
HashMap keeps the table length a power of two because then the bucket index is just n minus one AND hash, a single cheap instruction, instead of an integer division, and it never produces a negative index.
Then, if they want more
It also makes resizing simple: when the table doubles, the new mask has one more bit, so each entry either stays at index i or moves to i plus the old capacity, depending on the bit hash AND oldCap, and Java 8 splits each bucket into a lo list and a hi list without recomputing anything.
The cost is that only the low bits of the hash choose the bucket, so two hashes that differ only in the high bits would always collide. To reduce that, HashMap spreads the hash with h XOR h shifted right by 16, which folds the upper half into the lower half for the price of one shift and one XOR.
A prime-sized table with modulo is more forgiving of a poor hashCode because the remainder depends on all the bits, but it pays a division on every lookup.
The consequence for key classes is that a hash whose variation sits in only a few bits, for example multiples of a large power of two or an XOR of fields that cancel out, still clusters into a few buckets. Those buckets become long lists or red-black trees, so lookups slow down.
I make sure key hashes use the 31 times h plus field pattern, as records do.
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 "HashMap keeps its table length a power of two and indexes with (n - 1) & hash instead of...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/9ebcf9bcc0/