java.util.BitSet 類

從 1.7 開始,有一個 java.util.BitSet 類,它提供簡單且使用者友好的位儲存和操作介面:

final BitSet bitSet = new BitSet(8); // by default all bits are unset

IntStream.range(0, 8).filter(i -> i % 2 == 0).forEach(bitSet::set); // {0, 2, 4, 6}

bitSet.set(3); // {0, 2, 3, 4, 6}

bitSet.set(3, false); // {0, 2, 4, 6}

final boolean b = bitSet.get(3); // b = false

bitSet.flip(6); // {0, 2, 4}

bitSet.set(100); // {0, 2, 4, 100} - expands automatically

BitSet 實現了 ClonableSerializable,並且在引擎蓋下所有位值都儲存在 long[] words 欄位中,它會自動擴充套件。

它還支援整套邏輯運算 andorxorandNot

bitSet.and(new BitSet(8));
bitSet.or(new BitSet(8));
bitSet.xor(new BitSet(8));
bitSet.andNot(new BitSet(8));