百度到的BitSet相關的都寫的很高大上,是以就按自己的了解寫了這個自我感覺比較通俗的的解釋
如果想看高大上的可以點下面的連結
https://blog.csdn.net/haojun186/article/details/8482343
BitSet 裡面有一個Long數組,放入數字除以64取整則表示這個數字在Long數組的下标,且用餘數進行計算。 set方法:比如放入一個3,則把1左移三位(1000)并且 “|" 上Long[0]裡面的值(0)放入 Long[0]. 如果此時再放入一個5則把1左移5位(100000) 并且 “|" 上Long[0]裡面的值(101000)放入Long[0], 如果在放入同樣的值結果不變. 而假如這個時候放入一個65,則由于66除以64取整是1,取餘2,則此時把1左移餘數2(100) 并且 “|“ Long[1]( 取整的1為前面取整所得)裡面的值(0)放入Long[1]
get方法:之後假設從BitSet裡面擷取3,則會把1左移3位(1000) 然後 &”Long[0]裡的值(101000) 結果為1000不為0表示BitSet裡存在3, 而假設擷取的是4(10000) "&"(101000)結果為0表示不存在4。擷取66同理。
set的值 | 放入words的下标wordIndex | words[wordIndex]的二進制值 |
3 | 100 | |
5 | 10100 | |
6 | 110100 | |
67 | 1 | 1000 |
69 | 1 | 101000 |
129 | 2 | 1 |
get的值 | 下标wordIndex | words[wordIndex]的二進制值 | 結果 |
3 | 110100 | 100 |110100 = 100 | |
4 | 110100 | 1000 |110100 = 0 | |
6 | 110100 | 100000 |110100 = 100000 | |
67 | 1 | 1000 | 1000 |101000= 1000 |
68 | 1 | 11000 | 10000|101000=0 |
public void set(int bitIndex){
if(bitIndex< 0)
throw new IndexOutOfBoundsException("bitIndex < 0: "+bitIndex);
/*計算bitIndex存需要存放words(long)數組裡的下标(bitIndex除以64取整)*/
int wordIndex=wordIndex(bitIndex);
/*好像是用于記錄目前使用的最大下标*/
expandTo(wordIndex);
/*把1左移bitIndex位并且 “|” 上words數組裡wordIndex位置的值*/
words[wordIndex]|=(1L<<bitIndex); // Restores invariants
checkInvariants();
}
public void set(int bitIndex){
if(bitIndex< 0)
throw new IndexOutOfBoundsException("bitIndex < 0: "+bitIndex);
/*計算bitIndex存需要存放words(long)數組裡的下标(bitIndex除以64取整)*/
int wordIndex=wordIndex(bitIndex);
/*好像是用于記錄目前使用的最大下标*/
expandTo(wordIndex);
/*把1左移bitIndex位如果是66實際是左移2位并且 “|” 上words數組裡wordIndex位置的值*/
words[wordIndex]|=(1L<<bitIndex); // Restores invariants
checkInvariants();
}