Made the bulk clear() fast like bulk set() and flip() for BitSet.

This commit is contained in:
Mike Keesey 2012-07-05 22:16:19 -06:00
parent 990f4fd154
commit 9c9ee5c26d
2 changed files with 46 additions and 26 deletions

View File

@ -86,6 +86,24 @@ public class BitSet implements Serializable, Cloneable {
}
}
private void enlarge(int newPartition) {
if (bits == null || bits.length < (newPartition + 1)) {
long[] newBits = new long[newPartition + 1];
if (bits != null) {
System.arraycopy(bits, 0, newBits, 0, bits.length);
}
bits = newBits;
}
}
public boolean get(int index) {
int pos = longPosition(index);
if (pos < bits.length) {
return (bits[pos] & bitPosition(index)) != 0;
}
return false;
}
public void flip(int index) {
flip(index, index+1);
}
@ -103,31 +121,6 @@ public class BitSet implements Serializable, Cloneable {
}
}
private void enlarge(int newPartition) {
if (bits == null || bits.length < (newPartition + 1)) {
long[] newBits = new long[newPartition + 1];
if (bits != null) {
System.arraycopy(bits, 0, newBits, 0, bits.length);
}
bits = newBits;
}
}
public void clear(int index) {
int pos = longPosition(index);
if (pos < bits.length) {
bits[pos] &= (MASK ^ bitPosition(index));
}
}
public boolean get(int index) {
int pos = longPosition(index);
if (pos < bits.length) {
return (bits[pos] & bitPosition(index)) != 0;
}
return false;
}
public void set(int index) {
int pos = longPosition(index);
enlarge(pos);
@ -143,9 +136,18 @@ public class BitSet implements Serializable, Cloneable {
}
}
public void clear(int index) {
int pos = longPosition(index);
if (pos < bits.length) {
bits[pos] &= (MASK ^ bitPosition(index));
}
}
public void clear(int start, int end) {
for (int i = start; i < end; i++) {
clear(i);
MaskInfoIterator iter = new MaskInfoIterator(start, end);
while (iter.hasNext()) {
MaskInfo info = iter.next();
bits[info.partitionIndex] &= (MASK ^ info.mask);
}
}

View File

@ -48,6 +48,7 @@ public class BitsetTest {
assertEquals("after 100, 102 is empty", 102, bits.nextClearBit(100));
testFlip();
testClear();
BitSet expandingSet = new BitSet();
//should force us to have 3 partitions.
@ -80,6 +81,23 @@ public class BitsetTest {
assertTrue("70 should be false", !bitset.get(70));
}
private static void testClear() {
BitSet bitset = new BitSet();
bitset.set(0, 20);
assertCardinality(bitset, 20);
bitset.clear(1);
assertTrue("bit 1 should be 0", !bitset.get(1));
assertCardinality(bitset, 19);
bitset.clear(0, 3);
assertTrue("bit 0 should be 0", !bitset.get(0));
assertTrue("bit 1 should be 0", !bitset.get(1));
assertTrue("bit 2 should be 0", !bitset.get(2));
assertTrue("bit 3 should be 1", bitset.get(3));
assertCardinality(bitset, 17);
}
static void assertTrue(String msg, boolean flag) {
if (flag) {
System.out.println(msg + " : OK.");