Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java BitSet: distinguish logical length, capacity, and set-bit count

Last updated: 7 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

BitSet.length returns one beyond the highest set index, cardinality counts true bits, and size reports implementation storage capacity. These values answer different questions.

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

Java
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
compact sets and views
bitset-length-versus-cardinality
Storage details