Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

util.BitSet: practical reference

util.BitSet: practical reference: BitSet is a growable packed bit vector whose logical length is the highest set bit plus one, not its storage capacity.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.util.BitSet

BitSet is a growable packed bit vector whose logical length is the highest set bit plus one, not its storage capacity.

Use BitSet for dense non-negative integer flags and efficient mutable set algebra through and, or, xor, andNot, and range operations.

length is one plus the highest set bit and is zero when no bit is set; size reports implementation storage and is not the logical domain size. BitSet is not thread-safe.

All bits start false and storage grows automatically. Negative indexes throw IndexOutOfBoundsException, while toLongArray omits trailing zero words.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var bits = new java.util.BitSet();
        bits.set(1);
        bits.set(3);
        System.out.println(bits.cardinality());
    }
}

Result

2

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources