Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is BitSet.get() in Java?

abhilash

get() is an instance method of the BitSet used to get the bit at a given index or bits from a range of the index. There are two variations of the method. They are:

  • get(int bitIndex)
  • get(int fromIndex, int toIndex)

The get method is defined in the BitSet class. The BitSet class is defined in the java.util package. To import the BitSet class, check the following import statement.

import java.util.BitSet;

The get(int bitIndex) method

The get(int bitIndex) method returns the bit value at the given index.


public boolean get(int bitIndex)

Parameters

  • int bitIndex: The bit index.

Return value

This method returns the boolean value at the given index.

Code

import java.util.BitSet;

public class Main{

    public static void main(String[] args) {
        // Create empty BitSet object
        BitSet bitSet = new BitSet();

        // Set the bit at index 2
        bitSet.set(2);

        // index value
        int index = 2;

        // Use the get method to print the bit at given index
        System.out.printf("%s.get(2) = %s" , bitSet, bitSet.get(index));
        System.out.println();

        index = 4;
        // Use the get method to print the bit at given index
        System.out.printf("%s.get(2) = %s" , bitSet, bitSet.get(index));

    }
}

The get(int fromIndex, int toIndex) method

The get(int fromIndex, int toIndex) method returns a new BitSet object composed of bits from the fromIndex (inclusive) to toIndex (exclusive).


public BitSet get(int fromIndex, int toIndex)

Parameters

  • int fromIndex: The index of the first bit.
  • int toIndex: The index of the last bit.

Return value

This method returns a BitSet object.

Code

import java.util.BitSet;

public class Main{

    public static void main(String[] args) {
        // Create empty BitSet object
        BitSet bitSet = new BitSet();

        // Set the bit at index 2
        bitSet.set(3);

        // From index value
        int fromIndex = 2;

        // To index value
        int toIndex = 5;

        // Use the get method to print the bits from fromIndex to TtIndex
        System.out.printf("%s.get(%s, %s) = %s" , bitSet, fromIndex, toIndex, bitSet.get(fromIndex, toIndex));
    }
}

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring