import java.util.BitSet;
import java.util.Objects;public class MyBloomFilter {//位数组的大小private static final int DEFAULT_SIZE=2<<24;//创建6个不同的哈希函数private static final int[] SEEDS=new int[]{3,13,46,71,91,134};//位数组private BitSet bits=new BitSet(DEFAULT_SIZE);//包含6个hash函数的数组private SimpleHash[] func=new SimpleHash[SEEDS.length];//初始化多个包含hash函数的类的数组,每个类中的hash函数都不一样public MyBloomFilter(){for (int i=0;i< SEEDS.length;i++){func[i]=new SimpleHash(DEFAULT_SIZE,SEEDS[i]);}}//将元素添加到位数组public void add(Object value){for (SimpleHash f:func){bits.set(f.hash(value),true);}}//判断指定元素是否存在于位数组public boolean contains(Object value){boolean ret=true;for (SimpleHash f: func){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(Object o ){int h;return (o==null)?0:Math.abs(seed * (cap - 1) & ((h = o.hashCode()) ^ (h >>> 16)));}}}
public class Main {public static void main(String[] args) {String value1 = "https://javaguide.cn/";String value2 = "https://github.com/Snailclimb";MyBloomFilter filter=new MyBloomFilter();System.out.println(filter.contains(value1));System.out.println(filter.contains(value2));filter.add(value1);filter.add(value2);System.out.println(filter.contains(value1));System.out.println(filter.contains(value2));}
}