flip(int, int): This method is available in java.util.BitSet class of Java.
Syntax:
void java.util.BitSet.flip(int fromIndex, int toIndex)
This method takes two arguments of type int as its parameters. This method sets each bit from the specified fromIndex (inclusive) to the specified toIndex (exclusive) to the complement of its current value.
Parameters: Two parameters are required for this method.
fromIndex: index of the first bit to flip.
toIndex: index after the last bit to flip.
Throws:
IndexOutOfBoundsException - if fromIndex is negative, or toIndex is negative, or fromIndex is larger than toIndex.
Approach 1: When no exception
Java
import java.util.BitSet;public class BitSetflip2 {public static void main(String[] args) {BitSet bitSet = new BitSet(4);bitSet.set(1);bitSet.set(2);bitSet.set(4);bitSet.set(5);bitSet.set(6);bitSet.set(10);int fromIndex = 1;int toIndex = 5;bitSet.flip(fromIndex, toIndex);System.out.println(bitSet.clone());}}
Output:
{3, 5, 6, 10}
Approach 2: IndexOutOfBoundsException
Java
import java.util.BitSet;public class BitSetflip2 {public static void main(String[] args) {BitSet bitSet = new BitSet(4);bitSet.set(1);bitSet.set(2);bitSet.set(4);bitSet.set(5);bitSet.set(6);bitSet.set(10);int fromIndex = 6, toIndex = 5;bitSet.flip(fromIndex, toIndex);System.out.println(bitSet.clone());}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex: 6 > toIndex: 5 at java.base/java.util.BitSet.checkRange(BitSet.java:369) at java.base/java.util.BitSet.flip(BitSet.java:407)
No comments:
Post a Comment