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