栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现简易版布隆过滤器

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现简易版布隆过滤器

public class BloomFilters {

    
    private int arraySize;

    
    private int[] array;

    public BloomFilters(int arraySize){
        this.arraySize = arraySize;
        this.array = new int[arraySize];
    }

    public void add(String key){
        int hash1 = hashcode_1(key);
        int hash2 = hashcode_2(key);
        int hash3 = hashcode_3(key);
        array[hash1 % arraySize] = 1;
        array[hash2 % arraySize] = 1;
        array[hash3 % arraySize] = 1;
    }

    public boolean mightContain(String code){
        int hash1 = hashcode_1(code);
        int hash2 = hashcode_2(code);
        int hash3 = hashcode_3(code);
        return array[hash1 % arraySize] == 1 && array[hash2 % arraySize] == 1 && array[hash3 % arraySize] == 1;
    }

    
    private int hashcode_1(String key){
        int hash = 0;
        for(int i = 0; i < key.length(); i++){
            hash += 33 + key.charAt(i);
        }
        return Math.abs(hash);
    }

    
    private int hashcode_2(String data) {
        final int p = 16777619;
        int hash = (int) 2166136261L;
        for (int i = 0; i < data.length(); i++) {
            hash = (hash ^ data.charAt(i)) * p;
        }
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;
        return Math.abs(hash);
    }

    
    private int hashcode_3(String key) {
        int hash, i;
        for (hash = 0, i = 0; i < key.length(); ++i) {
            hash += key.charAt(i);
            hash += (hash << 10);
            hash ^= (hash >> 6);
        }
        hash += (hash << 3);
        hash ^= (hash >> 11);
        hash += (hash << 15);
        return Math.abs(hash);
    }

    public static void main(String[] args) {
        BloomFilters bloomFilters = new BloomFilters(10000000);
        for (int i = 0; i < 1000000; i++) {
            if(i == 12334 || i == 23223 || i == 2332){
                continue;
            }
            bloomFilters.add(i + "");
        }
        System.out.println(bloomFilters.mightContain("12334"));
        System.out.println(bloomFilters.mightContain("23223"));
        System.out.println(bloomFilters.mightContain("2332"));
        System.out.println(bloomFilters.mightContain("23324"));
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/673205.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号