BloomFilter一个简单的Java实现

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
        }
    }


}

 

你可能感兴趣的:(java)