Codectionary / Developer documentation / Java

BitSet Index Sets

BitSet represents a growable collection of boolean flags indexed by nonnegative integers. Logical operations efficiently combine groups of active indices. Save as Main.java and run with a Java 17+ JDK: java Main.java.

Syntax

bits.set(index); bits.and(other); bits.cardinality()

Examples

BitSet Index Sets

Save as Main.java and run with a Java 17+ JDK: java Main.java.

import java.util.BitSet;

public class Main {
  public static void main(String[] args) throws Exception {
    BitSet available = new BitSet();
    available.set(1); available.set(3); available.set(5);
    BitSet requested = new BitSet();
    requested.set(3); requested.set(4);
    BitSet shared = (BitSet) available.clone();
    shared.and(requested);
    System.out.println(shared);
    System.out.println(available.cardinality());
  }
}
  1. Expected output: {3} 3
  2. and mutates its receiver. Cloning first preserves the original set, whose three bits remain active.

Best practices

  • Distinguish cardinality (set bits) from length (highest set bit plus one).
  • Coordinate external synchronization when sharing mutable BitSet instances.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading