布隆算法是用来标记一个值是否存在,我们在很多场景下需要用到这样的算法,比方说使用redis做缓存时防止缓存穿透,gc中的卡表。
其原理就是用hash算法和位运算来实现,达到的效果是不存在的一定不存在,存在的不一定是真的存在
import java.util.BitSet;
/**
*
*/
public class Bloom {
private static final int DEFAULT_SIZE = 1 << 10; //最多记录十个值
private BitSet bits;
public Bloom() {
this(DEFAULT_SIZE);
}
public Bloom(int size) {
bits = new BitSet(size);
}
public void add(String value) {
if (value != null && !"".equals(value)) {
for (int i = 0; i < getHashCount(); i++) {
int index = hashCode(i, value) % bits.length();
bits.set(index, true);
}
}
}
public boolean contains(String value) {
if (value == null || "".equals(value)) {
return false;
}
for (int i = 0; i < getHashCount(); i++) {
int index = hashCode(i, value) % bits.length();
if (!bits.get(index)) {
return false;
}
}
return true;
}
private int hashCode(int seed, String value) {
int result = 0;
int len = value.length();
for (int i = 0; i < len; i++) {
char c = value.charAt(i);
result ^= ((seed + i * c) & 0xFF);
}
return Math.abs(result);
}
private int getHashCount() {
return 4; // 可根据需求调整hash函数次数
}
}