package com.zhong.demomaven.filter;
import java.util.BitSet;
/**
* 布隆過濾器-java實現
*/
public class BloomFilter {
private static final int DEFAULT_SIZE = 2 << 24; //位數
private static final int[] seeds = new int[]{5, 7, 11, 13, 31, 37, 61}; //一般使用質數
private BitSet bits = new BitSet(DEFAULT_SIZE); //位數組
private SimpleHash[] hashFunc = new SimpleHash[seeds.length];//hash函數數組
public BloomFilter() {
for (int i = 0; i < seeds.length; i++) {
hashFunc[i] = new SimpleHash(DEFAULT_SIZE, seeds[i]);//多個hash函數
}
}
/**
* add
*
* @param value
*/
public void add(String value) {
for (SimpleHash f : hashFunc) { //多個hash函數
bits.set(f.hash(value), true);
}
}
/**
* 判斷是否存在
*
* @param value
* @return
*/
public boolean contains(String value) {
if (value == null) {
return false;
}
boolean ret = true;
for (SimpleHash f : hashFunc) { //同時
ret = ret && bits.get(f.hash(value));
}
return ret;
}
/**
* 函數函數實現
*/
public static class SimpleHash {
private int cap;
private int seed;
public SimpleHash(int cap, int seed) {
this.cap = cap;
this.seed = seed;
}
public int hash(String value) {
int result = 0;
int len = value.length();
for (int i = 0; i < len; i++) {
result = seed * result + value.charAt(i);
}
return result & (cap - 1); // 等價於 result % cap
}
}
}