public class MyBitSet {
/**
* int类型长度是32bit 32 == 1<<5
*/
public static final int ADDRESS_BITS_PER_WORD = 5;
/**
* BitSet的长度
*/
private int size;
/**
* 这里用int数组来存储bit
*/
private int[] words;
public MyBitSet(int size) {
this.size = size;
words = new int[getIndex(size - 1) + 1];
}
/**
* 获取当前值应在数组的位置
*
* @param value
* @return
*/
public int getIndex(int value) {
return value >> ADDRESS_BITS_PER_WORD;
}
/**
* 对bit数组中某个位置置为1
*/
public void set(int value) {
//获取value应在words中的位置
int arrIndex = getIndex(value);
//将对应int的bit数组中相应位置bit值置为1
words[arrIndex] |= 1 << value;
}
/**
* 判断是否存在
*/
public boolean isHas(int value) {
int arrIndex = getIndex(value);
return (words[arrIndex] & (1 << value)) == (1 << value);
}
/**
* 删除
* @param value
*/
public void delete(int value) {
int arrIndex = getIndex(value);
boolean has = isHas(value);
if (has) {
words[arrIndex] ^= (1 << value);
}
}
public static void main(String[] args) {
// MyBitSet myBitSet = new MyBitSet(128);
// myBitSet.set(2);
// myBitSet.set(3);
// myBitSet.set(4);
// myBitSet.set(64);
// myBitSet.set(128);
// myBitSet.delete(64);
}
}