我的紧凑型布尔数组实现有什么问题?它不工作。测试失败了,所以我做错了一些按位运算。:(
public class CompactBooleanArray {
private final int size;
private final long[] bitmap;
public CompactBooleanArray(int size) {
this.size = size;
int numberOfLongs = (size + 63) / 64;
bitmap = new long[numberOfLongs];
}
public final void set(int index, boolean value) {
int longIndex = index >> 6;
int bitPosition = index & 63;
if (value) {
bitmap[longIndex] |= (1 << bitPosition);
} else {
bitmap[longIndex] &= ~(1 << bitPosition);
}
}
public final boolean get(int index) {
int longIndex = index >> 6;
int bitPosition = index & 63;
return (bitmap[longIndex] & (1 << bitPosition)) != 0;
}
public final int length() {
return size;
}
}
我的失败测试:
public class CompactBooleanArrayTest {
@Test
public void testSimple() {
int[] x = { 4, 56, 60 };
CompactBooleanArray array = new CompactBooleanArray(100);
for(int i : x) array.set(i, true);
for(int i = 0; i < array.length(); i++) {
System.out.println("I: " + i + " -> " + array.get(i));
if (check(i, x)) {
Assert.assertTrue(array.get(i));
} else {
Assert.assertFalse(array.get(i));
}
}
}
private boolean check(int value, int[] array) {
for(int i : array) {
if (value == i) return true;
}
return false;
}
}