我剛剛發現我的意外,那java.util.BitSet
沒有containsAll
的方法。我需要的,是類似如下:BitSet,no containsAll,最佳解決方法?
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;
}
什麼是用於實現containsAll
方法最好的變種?有沒有比這樣迭代更優雅的方式? (取自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;
}
爲什麼不只是做右移,按位AND,最後檢查結果是否爲1 – noMAD