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

Java BitSet nextSetBit: scan a bounded index range without walking gaps

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

BitSet.nextSetBit finds the next true bit at or after a starting index, returning -1 when none exists. A bounded scan must still enforce its end index and result cap.

Operational contract

The method returns at most 47 receipt slots in a half-open interval. It validates nonnegative ordered bounds, then jumps between set bits rather than testing every possible index. The loop stops before the exclusive upper bound. Because every visited bit is strictly less than an int upper bound, incrementing that bit cannot overflow here. A cap protects output memory and prevents one request from enumerating an enormous set. The input is caller-owned and must not be mutated concurrently without synchronization.

Failure case

Active slots are 3, 47, and 82. A scan of [40, 82) returns only 47. Slot 82 is outside the half-open range even though its bit is set.

Java code

Java
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Objects;

public class ReceiptSlotWindow {
    public static List<Integer> active(BitSet slots, int fromInclusive, int toExclusive) {
        Objects.requireNonNull(slots);
        if (fromInclusive < 0 || toExclusive < fromInclusive)
            throw new IllegalArgumentException("Invalid slot range");
        List<Integer> found = new ArrayList<>();
        for (int slot = slots.nextSetBit(fromInclusive);
                slot >= 0 && slot < toExclusive;
                slot = slots.nextSetBit(slot + 1)) {
            if (found.size() == 47) throw new IllegalStateException("Too many active slots");
            found.add(slot);
        }
        return List.copyOf(found);
    }
}

Performance and ownership cost

The scan visits K set bits and searches the underlying words across the requested span, rather than performing one test per missing index. Result memory is O(K) with K capped at 47. The returned immutable list copies its elements once.

Common Mistakes

  • Do not include the exclusive end slot.
  • Do not forget that nextSetBit returns -1 when no later bit exists.
  • Do not scan an unbounded range into an unbounded output list.

Connected lessons

java
compact sets and views
bitset-next-set-bit-range
Storage details