Skip to content

Commit 31dfff0

Browse files
committed
Create MyBloomFilter.java
1 parent 0f8981c commit 31dfff0

File tree

1 file changed

+90
-0
lines changed
  • source-code/start/hello-world/src/main/java/com/example/helloworld/controller

1 file changed

+90
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package com.example.helloworld.controller;
2+
3+
import java.util.BitSet;
4+
5+
public class MyBloomFilter {
6+
7+
public static void main(String[] args) {
8+
String value1 = "https://javaguide.cn/";
9+
String value2 = "https://github.com/Snailclimb";
10+
MyBloomFilter filter = new MyBloomFilter();
11+
System.out.println(filter.contains(value1));
12+
System.out.println(filter.contains(value2));
13+
filter.add(value1);
14+
filter.add(value2);
15+
System.out.println(filter.contains(value1));
16+
System.out.println(filter.contains(value2));
17+
}
18+
19+
/**
20+
* 位数组的大小
21+
*/
22+
private static final int DEFAULT_SIZE = 2 << 24;
23+
/**
24+
* 通过这个数组可以创建 6 个不同的哈希函数
25+
*/
26+
private static final int[] SEEDS = new int[]{3, 13, 46, 71, 91, 134};
27+
28+
/**
29+
* 位数组。数组中的元素只能是 0 或者 1
30+
*/
31+
private BitSet bits = new BitSet(DEFAULT_SIZE);
32+
33+
/**
34+
* 存放包含 hash 函数的类的数组
35+
*/
36+
private SimpleHash[] func = new SimpleHash[SEEDS.length];
37+
38+
/**
39+
* 初始化多个包含 hash 函数的类的数组,每个类中的 hash 函数都不一样
40+
*/
41+
public MyBloomFilter() {
42+
// 初始化多个不同的 Hash 函数
43+
for (int i = 0; i < SEEDS.length; i++) {
44+
func[i] = new SimpleHash(DEFAULT_SIZE, SEEDS[i]);
45+
}
46+
}
47+
48+
/**
49+
* 添加元素到位数组
50+
*/
51+
public void add(Object value) {
52+
for (SimpleHash f : func) {
53+
bits.set(f.hash(value), true);
54+
}
55+
}
56+
57+
/**
58+
* 判断指定元素是否存在于位数组
59+
*/
60+
public boolean contains(Object value) {
61+
boolean ret = true;
62+
for (SimpleHash f : func) {
63+
ret = ret && bits.get(f.hash(value));
64+
}
65+
return ret;
66+
}
67+
68+
/**
69+
* 静态内部类。用于 hash 操作!
70+
*/
71+
public static class SimpleHash {
72+
73+
private int cap;
74+
private int seed;
75+
76+
public SimpleHash(int cap, int seed) {
77+
this.cap = cap;
78+
this.seed = seed;
79+
}
80+
81+
/**
82+
* 计算 hash 值
83+
*/
84+
public int hash(Object value) {
85+
int h;
86+
return (value == null) ? 0 : Math.abs(seed * (cap - 1) & ((h = value.hashCode()) ^ (h >>> 16)));
87+
}
88+
89+
}
90+
}

0 commit comments

Comments
 (0)