什么';在Java中,这种使用long的位的紧凑布尔数组有什么问题?
我的紧凑布尔数组实现有什么问题?它不起作用。测试失败,因此我正在错误地执行某些位操作:(什么';在Java中,这种使用long的位的紧凑布尔数组有什么问题?,java,algorithm,bit-manipulation,bitwise-operators,Java,Algorithm,Bit Manipulation,Bitwise Operators,我的紧凑布尔数组实现有什么问题?它不起作用。测试失败,因此我正在错误地执行某些位操作:( 公共类CompactBooleanArray{ 私人最终整数大小; 私有最终长[]位图; 公共压缩布尔数组(整数大小){ 这个。大小=大小; 整数长度=(大小+63)/64; 位图=新长[numberOfLongs]; } 公共最终无效集(整数索引,布尔值){ int longIndex=指数>>6; int位位置=索引&63; 如果(值){ 位图[longIndex]|=(16; int位位置=索引&63
公共类CompactBooleanArray{
私人最终整数大小;
私有最终长[]位图;
公共压缩布尔数组(整数大小){
这个。大小=大小;
整数长度=(大小+63)/64;
位图=新长[numberOfLongs];
}
公共最终无效集(整数索引,布尔值){
int longIndex=指数>>6;
int位位置=索引&63;
如果(值){
位图[longIndex]|=(16;
int位位置=索引&63;
return(位图[longIndex]&(1不用尝试,我会说你的1移位对你来说很容易看到,对我来说很难。完全有道理!谢谢!
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;
}
}