BitSet的作用
- 使用BitSet可以节省存储空间
- 可以在o(1)的复杂度查询出某个值是否存在
Set方法
public void set(int bitIndex) {
if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
int wordIndex = wordIndex(bitIndex);
expandTo(wordIndex);
words[wordIndex] |= (1L << bitIndex); // Restores invariants
checkInvariants();
}
BitSet使用一个long类型的数组。即set方法中的words数组。
private static int wordIndex(int bitIndex) {
return bitIndex >> ADDRESS_BITS_PER_WORD;
}
wordIndex方法用于计算输入值在long数组中的位置,其中ADDRESS_BITS_PER_WORD=6,由于long类型的值占64位,64=2^6,因此,bitIndex>>ADDRESS_BITS_PER_WORD=>bitIndex/64。由于每个long类型的元素只能够标记64个数字,因此,wordIndex这个函数用于确定新添加的数应该由哪个long类型 的数来标记。
//该方法主要用于扩容
private void expandTo(int wordIndex) {
int words