Question

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;
}
Was it helpful?

Solution

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)
}

OTHER TIPS

For containsAll you are looking to see if every element within one bitset is within the other.

The loop will certainly work to do this. If you had access to the underlying data structures you could use bitwise operations but unfortunately you don't have that.

You may get a performance gain by doing toLongArray on both bitsets and then doing bit operations on each long - but the cost to generate the array most likely counteracts the benefits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top