Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BitSet, no containsAll, best workaround?

Tags:

java

bitset

I just discovered to my surprise, that java.util.BitSet has no containsAll method. What I need, is something like the following:

BitSet s1 = newBitSet(1, 2, 3, 4, 6);
BitSet s2 = newBitSet(1, 2, 3, 4);
BitSet s3 = newBitSet(1, 2, 3, 4, 5);
assertTrue(containsAll(s1, s2));
assertFalse(containsAll(s1, s3));

private static BitSet newBitSet(int... values) {
    BitSet bitSet = new BitSet();
    for (int value : values) {
        bitSet.set(value);
    }
    return bitSet;
}

What would be the best variant for implementing a containsAll method? Is there a more elegant way than iterating like this? (wird iteration code taken from JavaDoc)

private static boolean containsAll(BitSet s1, BitSet s2) {
    for (int i = s2.nextSetBit(0); i >= 0; i = s2.nextSetBit(i + 1)) {
        if (!s1.get(i)) {
            return false;
        }
    }
    return true;
}
like image 211
qqilihq Avatar asked Oct 18 '25 05:10

qqilihq


1 Answers

Your approach is fine. If you prefer to use more built-in BitSet methods, you can clone the first bit set and do a logical AND with the second then check for equality with the second.

private static boolean containsAll(BitSet s1, BitSet s2) {
    BitSet intersection = (BitSet) s1.clone();
    intersection.and(b2);
    return intersection.equals(s2)
}
like image 61
Brandon Avatar answered Oct 19 '25 21:10

Brandon