BitSet之爲何用long保存信息

BitSet內部使用long[] words來保存位信息。咋看之下並不理解緣由,在解讀set(int bitIndex)以後彷佛有了一些領悟。數組

public void set(int bitIndex) {it

if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);io

//用來計算應將bitIndex對應保存到哪一個位置。long佔用4個字節,64位(2的6次方),所以計算bitIndex對應着long數組的第幾位。margin

int wordIndex = wordIndex(bitIndex);static

//判斷是否須要擴容。
expandTo(wordIndex);word

//保存信息,將開關信息寫入對應long的位信息當中。ant

words[wordIndex] |= (1L << bitIndex); // Restores invariantsnew

checkInvariants();
}return

private static int wordIndex(int bitIndex) {
return bitIndex >> ADDRESS_BITS_PER_WORD;
}void

相關文章
相關標籤/搜索