#转自https://www.oschina.net/code/snippet_196697_36379#感谢~~~~~~~
/*这是以前遇到过的一道题目,最近在开源中国找到了比较简单的解决方法。*/
此类是从asp.net源代码中找到的一个很有用的类。现将此类翻译成java。
一个SimpleBitVector32类型的对象能保存32个标志位,相当于32个boolean类型的变量,但在SimpleBitVector32内部只是使用了一个int类型的字段,这样就用一个int类型的变量来替代32个boolean类型的变量,大大节省了内存开销。
/**
* Created by Leon on 2017/5/21.
*/
public class SimpleBitVector32
{
private int data;
public int getIntegerValue(){
return this.data;
}
public void setIntegerValue(int value){
this.data = value;
}
public boolean getThis(int bit){
return (this.data & bit) == bit;
}
public void setThis(int bit, boolean value){
int num = this.data;
if (value)
this.data = num | bit;
else
this.data = num & ~bit;
}
public int getThis(int mask, int offset){
return (this.data & mask) >> offset;
}
public void setThis(int mask, int offset, int value){
this.data = this.data & ~mask | value << offset;
}
public SimpleBitVector32(int data){
this.data = data;
}
public void set(int bit){
this.data |= bit;
}
public void clear(int bit){
this.data &= ~bit;
}
}
测试代码:
/**
* Created by Leon on 2017/5/21.
*/
public class Main {
public static void main(String[] args) {
SimpleBitVector32 data = new SimpleBitVector32(0);
System.out.println("The old boolean value at index 0:" + data.getThis(1));
System.out.println("The old boolean value at index 1:" + data.getThis(2));
System.out.println("The old boolean value at index 2:" + data.getThis(2*2));
System.out.println("The old boolean value at index 3:" + data.getThis(2*2*2));
System.out.println("The old boolean value at index 3:" + data.getThis(2*2*2*2));
System.out.println("The old boolean value at index 5:" + data.getThis(2*2*2*2*2));
System.out.println();
data.setThis(1, true);
data.setThis(2, false);
data.setThis(2*2, true);
data.setThis(2*2*2, false);
data.setThis(2*2*2*2, true);
data.setThis(2*2*2*2*2, false);
System.out.println("The new boolean value at index 0:" + data.getThis(1));
System.out.println("The new boolean value at index 1:" + data.getThis(2));
System.out.println("The new boolean value at index 2:" + data.getThis(2*2));
System.out.println("The new boolean value at index 3:" + data.getThis(2*2*2));
System.out.println("The new boolean value at index 4:" + data.getThis(2*2*2*2));
System.out.println("The new boolean value at index 5:" + data.getThis(2*2*2*2*2));
System.out.println("The value inside SimpleBitVector32 is:" + data.getIntegerValue());
System.out.print("//");
for (int i = 31; i >= 0; i--) {
System.out.print(((data.getIntegerValue() & (1 << i)) >>> i));
}
}
}