Example #1
0
  public void andNot(BitSet set) {
    // a & !a is false
    if (this == set) {
      // all falses result in an empty BitSet
      clear();
      return;
    }

    // trim the second set to avoid extra work
    trimToSize(array);
    int length = array.length();

    // truth table
    //
    // case | a | b | !b | a & !b | change?
    // 1 | false | false | true | false | a is already false
    // 2 | false | true | false | false | a is already false
    // 3 | true | false | true | true | a is already true
    // 4 | true | true | false | false | set a to false
    //
    // we only need to change something in case 4
    // whenever b is true, a should be false, so iterate over set b
    int index = 0;
    while ((index = nextSetWord(set.array, index)) != -1) {
      setWord(array, index, getWord(array, index) & ~set.array.get(index));
      if (++index >= length) {
        // nothing further will affect anything
        break;
      }
    }
  }
Example #2
0
  public int nextSetBit(int fromIndex) {
    checkIndex(fromIndex);

    int index = wordIndex(fromIndex);

    // check the current word
    int word = getWord(array, index);
    if (word != 0) {
      for (int i = bitOffset(fromIndex); i < 32; i++) {
        if ((word & (1 << i)) != 0) {
          return (bitIndex(index)) + i;
        }
      }
    }
    index++;

    // find the next set word
    trimToSize(array);
    index = nextSetWord(array, index);
    if (index == -1) {
      return -1;
    }

    // return the next set bit
    return (bitIndex(index)) + Integer.numberOfTrailingZeros(array.get(index));
  };
Example #3
0
  public void and(BitSet set) {
    // a & a is just a
    if (this == set) {
      return;
    }

    // trim the second set to avoid extra work
    trimToSize(set.array);

    // check if the length is longer than otherLength
    int otherLength = set.array.length();
    if (array.length() > otherLength) {
      // shrink the array, effectively ANDing those bits to false
      setLengthWords(array, otherLength);
    }

    // truth table
    //
    // case | a | b | a & b | change?
    // 1 | false | false | false | a is already false
    // 2 | false | true | false | a is already false
    // 3 | true | false | false | set a to false
    // 4 | true | true | true | a is already true
    //
    // we only need to change something in case 3, so iterate over set a
    int index = 0;
    while ((index = nextSetWord(array, index)) != -1) {
      setWord(array, index, array.get(index) & getWord(set.array, index));
      index++;
    }
  }