一.源码
1.构造方法
private long[] words;
public BitSet() {
// 64
initWords(BITS_PER_WORD);
}
public BitSet(int nbits) {
initWords(nbits);
}
private void initWords(int nbits) {
words = new long[wordIndex(nbits-1) + 1];
}
private static int wordIndex(int bitIndex) {
// bitIndex >> 6 == bitIndex / 64
return bitIndex >> ADDRESS_BITS_PER_WORD;
}
2.set
public void set(int bitIndex, boolean value) {
if (value)
set(bitIndex);
else
clear(bitIndex);
}
public void set(int bitIndex) {
// 数组下标
int wordIndex = wordIndex(bitIndex);
expandTo(wordIndex);
// 1L << 4 == 1L << (4 + 64) == 1L << (4 + 64 + 64)
words[wordIndex] |= (1L << bitIndex);
}
private void expandTo(int wordIndex) {
// 数组长度
int wordsRequired = wordIndex+1;
if (wordsInUse < wordsRequired) {
// 扩容
ensureCapacity(wordsRequired);
// 使用的数组元素个数
wordsInUse = wordsRequired;
}
}
private void ensureCapacity(int wordsRequired) {
if (words.length < wordsRequired) {
int request = Math.max(2 * words.length, wordsRequired);
words = Arrays.copyOf(words, request);
}
}
public void clear(int bitIndex) {
// 数组下标
int wordIndex = wordIndex(bitIndex);
// wordIndex下标的值为0,不需要操作
if (wordIndex >= wordsInUse)
return;
words[wordIndex] &= ~(1L << bitIndex);
recalculateWordsInUse();
}
private void recalculateWordsInUse() {
int i;
for (i = wordsInUse-1; i >= 0; i--)
if (words[i] != 0)
break;
wordsInUse = i+1;
}
3.get
public boolean get(int bitIndex) {
//数组下标
int wordIndex = wordIndex(bitIndex);
// wordIndex >= wordsInUse 直接返回false,因为wordIndex下标的值一定是0
return (wordIndex < wordsInUse)
&& ((words[wordIndex] & (1L << bitIndex)) != 0);
}