BitSet内部使用long[] words来保存位信息。咋看之下并不理解原因,在解读set(int bitIndex)之后似乎有了一些领悟。
public void set(int bitIndex) {
if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
//用来计算应将bitIndex对应保存到哪个位置。long占用4个字节,64位(2的6次方),因此计算bitIndex对应着long数组的第几位。
int wordIndex = wordIndex(bitIndex);
//判断是否需要扩容。
expandTo(wordIndex);
//保存信息,将开关信息写入对应long的位信息当中。
words[wordIndex] |= (1L << bitIndex); // Restores invariants
checkInvariants();
}
private static int wordIndex(int bitIndex) {
return bitIndex >> ADDRESS_BITS_PER_WORD;
}