mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 01:35:16 +08:00
Reduce memory usage of bloom filter (#3115)
This commit is contained in:

committed by
GitHub

parent
ba3c0319ed
commit
ec1ab53eea
@ -1,16 +1,18 @@
|
|||||||
package com.thealgorithms.datastructures.bloomfilter;
|
package com.thealgorithms.datastructures.bloomfilter;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.BitSet;
|
||||||
|
|
||||||
public class BloomFilter<T> {
|
public class BloomFilter<T> {
|
||||||
|
|
||||||
private int numberOfHashFunctions;
|
private int numberOfHashFunctions;
|
||||||
private int [] bitArray;
|
private BitSet bitArray;
|
||||||
private Hash<T>[] hashFunctions;
|
private Hash<T>[] hashFunctions;
|
||||||
|
|
||||||
public BloomFilter(int numberOfHashFunctions, int n) {
|
public BloomFilter(int numberOfHashFunctions, int n) {
|
||||||
this.numberOfHashFunctions = numberOfHashFunctions;
|
this.numberOfHashFunctions = numberOfHashFunctions;
|
||||||
hashFunctions = new Hash[numberOfHashFunctions];
|
hashFunctions = new Hash[numberOfHashFunctions];
|
||||||
bitArray = new int[n];
|
bitArray = new BitSet(n);
|
||||||
insertHash();
|
insertHash();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -22,13 +24,15 @@ public class BloomFilter<T> {
|
|||||||
|
|
||||||
public void insert(T key) {
|
public void insert(T key) {
|
||||||
for (Hash<T> hash : hashFunctions){
|
for (Hash<T> hash : hashFunctions){
|
||||||
bitArray[hash.compute(key) % bitArray.length] = 1;
|
int position = hash.compute(key) % bitArray.size();
|
||||||
|
bitArray.set(position);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean contains(T key) {
|
public boolean contains(T key) {
|
||||||
for (Hash<T> hash : hashFunctions){
|
for (Hash<T> hash : hashFunctions){
|
||||||
if (bitArray[hash.compute(key) % bitArray.length] == 0){
|
int position = hash.compute(key) % bitArray.size();
|
||||||
|
if (!bitArray.get(position)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user