Java Utility Library

Java BitSet - set() Method



The java.util.BitSet.set() method is used to set the bit at the specified index to the specified value in the given BitSet.

Syntax

public void set(int bitIndex, boolean value)

Parameters

bitIndex Specify a bit index.
value Specify a boolean value to set.

Return Value

void type.

Exception

Throws IndexOutOfBoundsException, if the specified index is negative.

Example:

In the example below, the java.util.BitSet.set() method is used to assign values in the given BitSet by setting the bit at the specified index to 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(10);
    BSet.set(20);
    BSet.set(30);
    BSet.set(40);
    BSet.set(50);

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

    //setting more values using set method
    BSet.set(40, false);
    BSet.set(50, false); 
    BSet.set(45, true);
    BSet.set(55, true);       

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

The output of the above code will be:

BSet contains: {10, 20, 30, 40, 50}
BSet contains: {10, 20, 30, 45, 55}

❮ Java.util - BitSet