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;
}
?