BitSet源碼的解讀

  小G今天看下布隆過濾器(有誤差),主要判斷集合是否存在,其實布隆裏面有一個知識點,就是BitSet
我今天先說明下bitSet後續有時間我在寫下布隆過濾器
首先看下java.util.BitSet

  1. set方法
public void set(int bitIndex) {
    if (bitIndex < 0)
        throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
      // 進去可以看到bitIndex >> ADDRESS_BITS_PER_WORD; 右移動6,也就是2^6次方,64個數組
    int wordIndex = wordIndex(bitIndex);
    //在下面有詳細說明
    expandTo(wordIndex);
     //在下面有詳細說明
    words[wordIndex] |= (1L << bitIndex); // Restores invariants
     //這個就是一個檢測數據
    checkInvariants();
}

expandTo(wordIndex)解釋看下面

private void expandTo(int wordIndex) {
    int wordsRequired = wordIndex+1;
        //放的數據, 比較下數組的下座標是否已經超出
    if (wordsInUse < wordsRequired) {
        //copy數組,超過後新增2倍
        ensureCapacity(wordsRequired);
        wordsInUse = wordsRequired;
    }
}

words[wordIndex] |= (1L << bitIndex)解釋看下面

這個我們講下這個,轉化下:words[wordIndex] =words[wordIndex] ||(1L << bitIndex);
先看下(1L << bitIndex) 說明:左移動數組的bitIndex 位,然後爲1,怎麼說呢?看下面吧
1L<<1 轉化爲2進制,10,
1L<<2 轉化爲2進制,100,
1L<<3 轉化爲2進制,1000,
這個是否明白,哈,然在看看下words[wordIndex] ||(1L << bitIndex),小G囉嗦下,bitset存的就是1或0的2進制數組,0代表爲沒有純在這個集合,
1代表存在這個集合
這下是不是明白,就是我看看words[wordIndex]的數組是不是1,如有爲1還是1(小G在囉嗦下,或就是兩個只有有一個是1就是1,多讀幾次就知道)

  1. 再來看下get就比較簡單
public boolean get(int bitIndex) {
    if (bitIndex < 0)
        throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
    //檢測數據的assert
    checkInvariants();
    //獲取數組的位置
    int wordIndex = wordIndex(bitIndex);
        //  如果是爲0說明該書不存在
    return (wordIndex < wordsInUse)
        && ((words[wordIndex] & (1L << bitIndex)) != 0);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章