BitSet.length returns one beyond the highest set index, cardinality counts true bits, and size reports implementation storage capacity. These values answer different questions.
Java BitSet: distinguish logical length, capacity, and set-bit count
Operational contract
The method reports the highest active receipt slot and total active slots without mistaking allocated capacity for a business identifier. An empty BitSet has length zero, so the highest index is represented as -1. A sparse set with only slot 82 active has cardinality one and length 83. BitSet grows to hold high indexes, which can make a single erroneous ID expensive. Validate identifiers before calling set; BitSet is not synchronized for concurrent mutation.
Failure case
The importer marks slot 82 and then clears it. Its logical length returns to zero even though its backing storage may remain allocated. Using size as the number of processed receipts would report capacity instead of work done.
Java code
import java.util.BitSet;
import java.util.Objects;
public class ActiveReceiptSlots {
public record Summary(int highestSlot, int activeCount) { }
public static Summary summarize(BitSet activeSlots) {
Objects.requireNonNull(activeSlots);
int logicalLength = activeSlots.length();
return new Summary(logicalLength == 0 ? -1 : logicalLength - 1,
activeSlots.cardinality());
}
}Performance and ownership cost
Computing cardinality scans the words used by the bit set, taking O(W) time for W stored machine words; highest-set-bit lookup is tied to that representation. The method adds O(1) result storage. A very high index can enlarge the underlying bit vector far beyond the number of true bits.
Common Mistakes
- Do not use size as the count of true bits.
- Do not return length as the highest index without subtracting one for a nonempty set.
- Do not set unvalidated huge indexes in a sparse business ID space.
Connected lessons
- Java BitSet nextSetBit: scan a bounded index range without walking gaps
- Java collection factories: rejected updates and shallow element ownership
- Arrays
- Java EnumSet complementOf: derive a default-deny capability set
- Java EnumSet: retain element type when a source collection is empty
- Java NavigableSet subSet: account for a live backed range
- Java specialized collections quiz
- Advanced Java
