java 实现bloomfilter

 https://blog.csdn.net/Acceptedxukai/article/details/7031899

public class btDemo2 {
    private static final int defSize = 1 << 16;//过滤器长度
    private static BitSet bitset = new BitSet(defSize);
    private static int[] seeds = new int[]{2, 3};//选取一串质数
    private static final bsFun[] fun = new bsFun[seeds.length];

    public btDemo2() {
        for (int i = 0; i < seeds.length; i++) {
            fun[i] = new bsFun(seeds[i], defSize);
        }
    }

    public void add(String url) {
        for (bsFun bsFun : fun) {
            bitset.set(bsFun.hash(url), true);
        }
    }

    public boolean contains(String url) {
        if (url == null)
            return false;
        boolean ret = true;
        for (bsFun bsFun : fun) {
            boolean bool = bitset.get(bsFun.hash(url));
            return bool && ret; //&跟&&区别 是&&会判断第一个条件,如果第一个条件false,那么就不会看第二个条件了
        }
        return false;
    }

    public static void main(String[] args) {
        btDemo2 bt = new btDemo2();
        String url1 = "www.baidu.com";
        String url2 = "www.sina.com";
        String url3 = "www.baidu.com";
        String url4="www.163.com";
        bt.add(url1);
        bt.add(url2);
        bt.add(url3);
        boolean iscon = bt.contains(url3);
        boolean isUrl4 = bt.contains(url4);
        System.out.println(iscon);
        System.out.println("url4:"+isUrl4);
    }


    class bsFun { //映射函数
        private int seed;
        private int len;

        public bsFun(int seed, int len) {
            this.seed = seed;
            this.len = len;
        }

        //计算hash
        public int hash(String url) {
            int result = 0;
            for (int i = 0; i < url.length(); i++) {
                result = result * seed + url.charAt(i);//字符串的每一位因子都计算进去
            }
            return (len - 1) & result;
        }
    }
}

 

你可能感兴趣的:(Java服务器开发)