Collections: BitSet packs booleans into 64-bit words

BitSet stores flags as bits inside a backing long[] instead of one boolean per slot, so length() reports one past the highest set bit and cardinality() counts how many are actually on.

Code
BitSet flags = new BitSet();
flags.set(5);
flags.set(64);
flags.set(150);
System.out.println("Set bits: " + flags);
System.out.println("Logical length (highest bit + 1): " + flags.length());
System.out.println("Bits actually on: " + flags.cardinality());
Output
Set bits: {5, 64, 150}
Logical length (highest bit + 1): 151
Bits actually on: 3
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms