Java.util.BitSet.set() method in Java
There are four variants of set() method.This article depicts about all of them, as follows:
1. set(int Index) : This method sets the bit at the specified index to true i.e adds a value.
Declaration :
public void set(int bitIndex)
Parameters :
Index : a bit index.
Result :
This method does not return a value.
Exception :
IndexOutOfBoundsException : if the specified index is negative.
import java.util.*;
public class BitSet1 {
public static void main(String[] args)
{
BitSet bset = new BitSet( 5 );
bset.set( 3 );
bset.set( 5 );
System.out.println( "The constructed bitset is : " + bset);
}
}
|
Output:
The constructed bitset is : {3, 5}
2. set(int num, boolean value) : This method sets the bit at the specified index to the specified value, if boolean value is true, value is added, else not added.
Declaration :
public void set(int num, boolean value)
Parameters :
num : a bit value.
value : a boolean value to set.
Return Value
This method does not return a value.
import java.util.*;
public class BitSet2 {
public static void main(String[] args)
{
BitSet bset = new BitSet( 5 );
bset.set( 3 , true );
bset.set( 5 , false );
bset.set( 7 , true );
bset.set( 4 , false );
System.out.println( "The constructed bitset is : " + bset);
}
}
|
Output:
The constructed bitset is : {3, 7}
3. set(int fromnum, int tonum) : This method sets the bits from the specified fromnum(inclusive) to the specified tonum(exclusive) to true, i.e adds the values fromnum to tonum-1.
Declaration :
public void set(int fromnum, int tonum)
Parameters :
fromnum : value to start insert.
tonum : value to end insertion.
Return Value :
This method does not return a value.
import java.util.*;
public class BitSet3 {
public static void main(String[] args)
{
BitSet bset = new BitSet( 9 );
bset.set( 3 , 9 );
System.out.println( "The constructed bitset is : " + bset);
}
}
|
Output:
The constructed bitset is : {3, 4, 5, 6, 7, 8}
4. set(int fromnum, int tonum, boolean value) : This method sets the bits from the specified fromnum (inclusive) to the specified tonum (exclusive) to the specified value i.e inserts fromnum to tonum-1 if boolean value passed is true, else doesn’t insert.
Declaration :
public void set(int fromnum, int tonum, boolean value)
Parameters :
fromnum : num to start inserting.
tonum : last number of insertion.
value : value to set the selected bits to.
Return Value :
This method does not return a value.
import java.util.*;
public class BitSet4 {
public static void main(String[] args)
{
BitSet bset = new BitSet( 9 );
bset.set( 3 , 9 , false );
bset.set( 5 , 11 , true );
System.out.println( "The constructed bitset is : " + bset);
}
}
|
Output:
The constructed bitset is : {5, 6, 7, 8, 9, 10}
Last Updated :
10 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...