Quick revision
The short answer
HashMap keeps its table size a power of two so it can pick a bucket with (n - 1) & hash instead of a slow modulo, and it spreads the hash with h ^ (h >>> 16) so the high bits influence that mask. BitSet stores bits in a long[] and finds set bits with Long.numberOfTrailingZeros, and RegularEnumSet packs up to 64 enum constants into a single long, so add and contains are single bit operations. Methods such as Integer.highestOneBit and numberOfLeadingZeros size capacities and are JIT intrinsics. All of this avoids division and branches on hot paths.
What to remember
In this answer, we saw how the JDK uses bits to stay fast. HashMap keeps power-of-two tables so (n - 1) & hash replaces modulo, spreads hashes with h ^ (h >>> 16) so high bits count, and splits buckets on resize with a single bit test. Capacities are rounded with numberOfLeadingZeros and highestOneBit, which are JIT intrinsics. BitSet packs bits into a long[] and finds set bits with numberOfTrailingZeros, and RegularEnumSet holds up to 64 constants in one long so add and contains are single bit operations. Together these avoid division and branches on the hottest paths.
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 size a power of two so it can pick a bucket with (n - 1) & hash instead of a slow modulo, and it spreads the hash with h ^ (h >>> 16) so the high bits influence that mask. BitSet stores bits in a long[] and finds set bits with Long.numberOfTrailingZeros, and RegularEnumSet packs up to 64 enum constants into a single long, so add and contains are single bit operations. Methods such as Integer.highestOneBit and numberOfLeadingZeros size capacities and are JIT intrinsics. All of this avoids division and branches on hot paths.
Why this question is asked
We rarely write bit manipulation ourselves in business code, but we depend on it all the time, because the JDK's core collections are built on it. Knowing where and why helps us predict performance, for example why an EnumSet beats a HashSet of enums by a wide margin, and why a bad hashCode can hurt a HashMap more than we expect. Interviewers ask this to see whether we understand the cost model of the classes we use, not just their API. In this answer, we will look at HashMap's hash spreading and masking, BitSet's word-based storage, EnumSet's single-long representation, the Integer and Long helper methods that are compiled into single instructions, and finally why these choices matter.
1HashMap: Power-of-Two Tables and Hash Spreading
HashMap's table length is always a power of two: 16, 32, 64 and so on. That choice exists for one reason. Choosing a bucket means reducing a 32-bit hash to a number between 0 and n - 1. The general way is hash % n, but integer division is one of the slowest arithmetic instructions, often 20 to 40 cycles, and % also returns negative results for negative hashes. When n is a power of two, n - 1 is a mask of all ones in the low bits, so (n - 1) & hash keeps exactly the low bits, gives the same result as a non-negative modulo, and costs one cycle.
But there is a catch. A mask only looks at the low bits, so hash codes that differ only in their high bits would all collide. That is common: Float keys, or objects whose hashCode is built from multiplied fields, can have variation mostly in the top bits. So HashMap first spreads the hash with h ^ (h >>> 16), which XORs the top 16 bits into the bottom 16. It is a single shift and XOR, cheap enough to do on every operation, and it lets the high bits influence the bucket.
Resizing uses the power of two again. When the table doubles, each entry either stays at index i or moves to i + oldCapacity, decided by the single bit hash & oldCapacity. HashMap splits each bucket into a low list and a high list with that one test, instead of recomputing every index.
2Sizing Capacities With highestOneBit and numberOfLeadingZeros
When we create new HashMap<>(1000), HashMap rounds the capacity up to the next power of two, 1024. The JDK computes that with Integer.numberOfLeadingZeros: it counts the zero bits above the highest set bit of cap - 1, and shifting -1 right by that count produces a mask of ones that, plus one, is the next power of two. Integer.highestOneBit(n) is the related method that returns n with only its highest bit kept. ArrayDeque and ConcurrentHashMap use similar calculations for their own power-of-two sizes.
numberOfLeadingZeros, numberOfTrailingZeros and bitCount are JIT intrinsics in HotSpot. The JIT replaces the Java method body with a single CPU instruction where one exists, such as LZCNT, TZCNT and POPCNT on x86-64 and CLZ on ARM. So these calls, which look like method calls in source code, cost about one cycle in compiled code. Check your JVM and CPU, but on mainstream servers this has been true for many years.
3BitSet: Bits Packed Into long Words
java.util.BitSet stores its bits in a long[] called words. Bit number i lives in word i >> 6, because each long holds 64 bits and shifting by 6 divides by 64, at position i & 63 within the word. Setting a bit is words[i >> 6] |= 1L << i; notice that Java masks a long shift count to 6 bits, so 1L << i already uses i mod 64 and the JDK relies on that. A million flags fit in 15,625 longs, about 125 KB, instead of about 1 MB for a boolean[] or tens of megabytes for a HashSet<Integer>.
Iterating over set bits is where the intrinsics shine. nextSetBit(from) skips empty words with one comparison each and, inside a non-zero word, finds the next set bit with Long.numberOfTrailingZeros, a single instruction, instead of testing 64 positions one by one. Operations like and, or and cardinality work a whole word at a time, 64 bits per instruction, with cardinality summing Long.bitCount over the words.
| Bit index i | Word i >> 6 | Position i & 63 | Operation |
|---|---|---|---|
| 3 | 0 | 3 | words[0] |= 1L << 3 |
| 70 | 1 | 6 | words[1] |= 1L << 6 |
| 999,999 | 15,624 | 63 | words[15624] |= 1L << 63 |
4EnumSet: A Whole Set in One long
EnumSet.noneOf(MyEnum.class) returns a RegularEnumSet when the enum has 64 or fewer constants, and a JumboEnumSet backed by a long[] when it has more. In RegularEnumSet the entire set is one long field. Each enum constant has an ordinal, its position in the declaration, and the constant is in the set when bit ordinal is 1. So add is elements |= 1L << ordinal, contains is (elements & (1L << ordinal)) != 0, size is Long.bitCount(elements), and containsAll or retainAll between two sets is a single AND.
Compare that with a HashSet<Day>: each contains call computes a hash, finds a bucket, follows a node and calls equals, and each element costs a node object of about 32 bytes. An EnumSet of any size costs one long plus a small object header. That is why EnumSet, and EnumMap, which is an array indexed by ordinal, are the recommended collections for enum keys.
5Why These Choices Matter for Performance
Collections sit on the hottest paths of most applications, so every cycle saved per operation is multiplied by billions of calls. The common thread in all these designs is avoiding two expensive things. Division is replaced by masking, which requires power-of-two sizes. Branches, especially unpredictable ones in loops over bits, are replaced by single-instruction intrinsics that find the next set bit or count bits directly. Packing data into words also improves memory locality: 64 flags in one cache line read instead of 64 separate objects.
This also gives us practical guidance. A hashCode whose differences are in the high bits still works thanks to spreading, but one that returns the same value for many keys cannot be rescued by any bit trick. Enum keys should use EnumSet and EnumMap. Dense sets of small integers should use BitSet or a library like RoaringBitmap rather than Set<Integer>. And when we need a fast modulo on a hot path of our own, rounding the size up to a power of two lets us use the same mask trick.
6Follow-up questions
Why does HashMap not just use a prime table size, which spreads hashes well with modulo?
Prime sizes do spread poor hashes well, which is why some other hash tables use them, but they require a real division on every lookup and make resizing more expensive. Java chose the cheaper mask with power-of-two sizes and compensates for weak low bits with the h ^ (h >>> 16) spread and with treeified buckets for bad collisions.
What happens if an enum has more than 64 constants?
EnumSet switches to JumboEnumSet, which uses a long[] with one word per 64 constants. Operations become loops over a few words, still very fast, and the choice is made automatically by the EnumSet factory methods.
Are these intrinsics available in every JVM?
They are standard in HotSpot on mainstream x86-64 and ARM servers, but intrinsics depend on the JVM and the CPU features available. The Java code is always correct; only the speed differs. Check with JMH or the JIT's diagnostic output if it matters for your platform.
7Conclusion
In this answer, we saw how the JDK uses bits to stay fast. HashMap keeps power-of-two tables so (n - 1) & hash replaces modulo, spreads hashes with h ^ (h >>> 16) so high bits count, and splits buckets on resize with a single bit test. Capacities are rounded with numberOfLeadingZeros and highestOneBit, which are JIT intrinsics. BitSet packs bits into a long[] and finds set bits with numberOfTrailingZeros, and RegularEnumSet holds up to 64 constants in one long so add and contains are single bit operations. Together these avoid division and branches on the hottest paths.
Open with
The clearest example is HashMap. Its table size is always a power of two so the bucket index can be computed as n minus one AND hash, a one-cycle mask, instead of a modulo, which is a slow division and can be negative.
Then, if they want more
Because the mask only looks at low bits, HashMap first spreads the hash with h XOR h unsigned-shifted right by 16, so keys that differ only in their high bits still land in different buckets. On resize, each entry either stays or moves by the old capacity depending on one bit, so buckets split without recomputing indexes.
Capacities are rounded up to a power of two using numberOfLeadingZeros, and that method, along with numberOfTrailingZeros and bitCount, is a JIT intrinsic that compiles to a single instruction like LZCNT or POPCNT.
BitSet stores bits in a long array, bit i in word i shifted right by six, and nextSetBit uses numberOfTrailingZeros to jump straight to the next set bit instead of testing each position.
RegularEnumSet, used for enums with up to 64 constants, is a single long where bit ordinal means the constant is present, so add, contains and containsAll are single bit operations, far cheaper than a HashSet. The point of all of these is to avoid division and unpredictable branches on paths that run billions of times.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. 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 "Explain where bit manipulation appears inside JDK classes such as HashMap, BitSet and...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/e08e6793af/