一.源码

1.构造方法

  1. private long[] words;
  2. public BitSet() {
  3. // 64
  4. initWords(BITS_PER_WORD);
  5. }
  6. public BitSet(int nbits) {
  7. initWords(nbits);
  8. }
  9. private void initWords(int nbits) {
  10. words = new long[wordIndex(nbits-1) + 1];
  11. }
  12. private static int wordIndex(int bitIndex) {
  13. // bitIndex >> 6 == bitIndex / 64
  14. return bitIndex >> ADDRESS_BITS_PER_WORD;
  15. }

2.set

  1. public void set(int bitIndex, boolean value) {
  2. if (value)
  3. set(bitIndex);
  4. else
  5. clear(bitIndex);
  6. }
  7. public void set(int bitIndex) {
  8. // 数组下标
  9. int wordIndex = wordIndex(bitIndex);
  10. expandTo(wordIndex);
  11. // 1L << 4 == 1L << (4 + 64) == 1L << (4 + 64 + 64)
  12. words[wordIndex] |= (1L << bitIndex);
  13. }
  14. private void expandTo(int wordIndex) {
  15. // 数组长度
  16. int wordsRequired = wordIndex+1;
  17. if (wordsInUse < wordsRequired) {
  18. // 扩容
  19. ensureCapacity(wordsRequired);
  20. // 使用的数组元素个数
  21. wordsInUse = wordsRequired;
  22. }
  23. }
  24. private void ensureCapacity(int wordsRequired) {
  25. if (words.length < wordsRequired) {
  26. int request = Math.max(2 * words.length, wordsRequired);
  27. words = Arrays.copyOf(words, request);
  28. }
  29. }
  30. public void clear(int bitIndex) {
  31. // 数组下标
  32. int wordIndex = wordIndex(bitIndex);
  33. // wordIndex下标的值为0,不需要操作
  34. if (wordIndex >= wordsInUse)
  35. return;
  36. words[wordIndex] &= ~(1L << bitIndex);
  37. recalculateWordsInUse();
  38. }
  39. private void recalculateWordsInUse() {
  40. int i;
  41. for (i = wordsInUse-1; i >= 0; i--)
  42. if (words[i] != 0)
  43. break;
  44. wordsInUse = i+1;
  45. }

3.get

  1. public boolean get(int bitIndex) {
  2. //数组下标
  3. int wordIndex = wordIndex(bitIndex);
  4. // wordIndex >= wordsInUse 直接返回false,因为wordIndex下标的值一定是0
  5. return (wordIndex < wordsInUse)
  6. && ((words[wordIndex] & (1L << bitIndex)) != 0);
  7. }