我的紧凑型 boolean 数组实现有什么问题?它不工作。测试失败,所以我错误地做了一些按位运算。 :(
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;
}
}
最佳答案
如果不尝试,我会说您的 1 << bitPosition 等移位失败,因为您没有使用 1L。即 1 << 50 = 0, 1L << 50 = 2^50th
关于java - 这个在 Java 中使用 long 的位的紧凑型 boolean 数组有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13784970/