布隆过滤器代码实现 java
时间: 2023-11-04 17:54:27 浏览: 89
布隆过滤器是一种用于判断一个元素是否存在于集合中的数据结构,它使用了位数组和多个哈希函数。以下是一个简单的Java实现示例:
```java
import java.util.BitSet;
public class BloomFilter {
private BitSet bitset;
private int size;
private int[] hashFunctions;
public BloomFilter(int size, int numHashFunctions) {
this.bitset = new BitSet(size);
this.size = size;
this.hashFunctions = new int[numHashFunctions];
}
public void add(String element) {
for (int i = 0; i < hashFunctions.length; i++) {
int hash = getHash(element, i);
bitset.set(hash);
}
}
public boolean contains(String element) {
for (int i = 0; i < hashFunctions.length; i++) {
int hash = getHash(element, i);
if (!bitset.get(hash)) {
return false;
}
}
return true;
}
private int getHash(String element, int hashFunctionIndex) {
int hash = element.hashCode();
hash ^= (hash >>> 20) ^ (hash >>> 12);
return (hash ^ (hash >>> 7) ^ (hash >>> 4) ^ hashFunctions[hashFunctionIndex]) % size;
}
}
```
阅读全文