Java Utility Library

Java BitSet - set() Method



The java.util.BitSet.set() method is used to set the bits from the specified fromIndex (inclusive) to the specified toIndex (exclusive) to the specified value in the given BitSet.

Syntax

public void set(int fromIndex, int toIndex, boolean value)

Parameters

fromIndex Specify the index of the first bit to be set.
toIndex Specify the index after the last bit to be set.
value Specify the value to set the selected bits to.

Return Value

void type.

Exception

Throws IndexOutOfBoundsException, if fromIndex is negative, or toIndex is negative, or fromIndex is larger than toIndex.

Example:

In the example below, the java.util.BitSet.set() method is used to assign values in the given BitSet by setting the bit in specified range of index to the specified value.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {   
    //creating a BitSet
    BitSet BSet = new BitSet();

    //populating BitSet
    BSet.set(1);
    BSet.set(2);
    BSet.set(3);
    BSet.set(4);
    BSet.set(5);
    BSet.set(6);    

    //printing BitSet
    System.out.println("BSet contains: " + BSet);

    //setting more values using set method
    BSet.set(4, 7, false);  
    BSet.set(11, 14, true); 

    //printing BitSet
    System.out.println("BSet contains: " + BSet);
  }
}

The output of the above code will be:

BSet contains: {1, 2, 3, 4, 5, 6}
BSet contains: {1, 2, 3, 11, 12, 13}

❮ Java.util - BitSet