Mangat Rai Modi Mangat Rai Modi - 3 months ago 14
Java Question

Java: BitSet comparison

Suppose we have two BitSet objects in Java with values as


How can we compare B1 and B2 to know that the value represented by B1 is greater than that by B2.

are logical operators (>,<,==) overloaded for BitSet? or Do I have to write my own implementation?

Update: just found that "The operator > is undefined for the argument type(s) java.util.BitSet, java.util.BitSet". Is there any built-in way to do so?


You can do it by xor-ing the two sets together, and comparing the length of the result to lengths of bit sets:

  • If xor is empty, bit sets are equal. You can bypass this operation by calling equals()
  • Otherwise, the length of xor result will be equal to the position of the most significant bit that is different between the two values.
  • Whichever of the two operands has this bit set is the greater one of the two.

Here is a sample implementation:

int compare(BitSet lhs, BitSet rhs) {
    if (lhs.equals(rhs)) return 0;
    BitSet xor = (BitSet)lhs.clone();
    int firstDifferent = xor.length()-1;
            return 0;

    return rhs.get(firstDifferent) ? 1 : -1;