咖啡汪日志——自己写的一个布隆过滤器(BloomFilter)

原理图:
在这里插入图片描述


import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 布隆过滤器
 * **
 *
 * @author: Yuezejian  Created in 2020/9/29 上午9:02
 * @modified By:
 */
public class BloomFilter implements Cloneable, Serializable {
    private static final long serialVersionUID = 482498820763181265L;
    private static byte[] data;
    private static final int INIT_CAPACITY_SIZE = 128;
    private float loadFactor = 0.75f;

    /**
     * Set the capacity 64 when we init the BloomFilter
     */
    public BloomFilter() {
        this.data = new byte[INIT_CAPACITY_SIZE];
    }

    /**
     * Apply the init capacity method when used the constructor to init the BloomFilter
     * @param initCapacity
     */
    public BloomFilter(int initCapacity) {
        this.data = new byte[initCapacity];
    }

    /**
     * Put the elements to byte[]
     * @param key
     */
    public void put(int key) {
        if (data.length+1 >= data.length * loadFactor) {
            data = reHash(data);
        }
        reSet(key);
    }

    /**
     * validate if contains the element
     * @param key
     * @return
     */
    public static boolean contains(int key) {
        int site1 = Math.abs(hash1(key) % data.length);
        int site2 = Math.abs(hash2(key) % data.length);
        int site3 = Math.abs(hash3(key) % data.length);
        return data[site1] * data[site2] * data[site3] == 1;
    }

    static final int hash1(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ ( h >>> 3);

    }

    static final int hash2(Integer key) {
       int h;
       return (key == null) ? 0 : (h = key.hashCode()) ^ ( h >>> 16);
    }

    static final int hash3(Integer key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 32);
    }

    static final byte[] reHash(byte[] b) {
        byte[] cor = new byte[oldCapacity + (oldCapacity >> 1)];
        System.arraycopy(data, 0, cor, 0, data.length);
        return cor;
    }

    private static void reSet(int a) {
        int site1 = Math.abs(a % data.length);
        int site2 = Math.abs(a % data.length);
        int site3 = Math.abs(a % data.length);
        data[site1] = data[site2] = data[site3] =1;
    }

}

位运算推荐:https://www.cnblogs.com/yrjns/p/11246163.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咖啡汪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值