public class BitMap {
private byte[] drums;
public BitMap(){
this(1024);
}
public BitMap(int size){
if(size <= 0)
throw new RuntimeException("BitMap长度应该大于0");
// size & 0x07 == size % 8 size >> 3 == size /= 8
int drumSize = (size & 0x07) == 0 ? size >> 3: (size >> 3)+1;
drums = new byte[drumSize];
}
public void add(int num){
int position = findDrumPosition(num);
drums[position] |= 1 << (num & 0x07);
}
public void remove(int num){
int position = findDrumPosition(num);
drums[position] &= ~(0 ^ 1 << (num & 0x07));
}
public boolean has(int num){
int position = findDrumPosition(num);
return ((drums[position] >> (num & 0x07)) & 0x01) == 1;
}
public void forEach(Consumer<Integer> exist, Consumer<Integer> noExist){
if(noExist == null)
noExist = e->{};
if(exist == null)
exist = e->{};
for (int i = 0; i < drums.length<<3; i++) {
if(!has(i))
noExist.accept(i);
else
exist.accept(i);
}
}
// 定位桶
private int findDrumPosition(int num){
if(num < 0 || num >= drums.length<<3)
throw new RuntimeException("存入的数据应该大于等于0且小于BitMap的长度");
return num >> 3;
}
}