Skip to content

Commit ec1ab53

Browse files
authored
Reduce memory usage of bloom filter (TheAlgorithms#3115)
1 parent ba3c031 commit ec1ab53

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
package com.thealgorithms.datastructures.bloomfilter;
22

33

4+
import java.util.BitSet;
5+
46
public class BloomFilter<T> {
57

68
private int numberOfHashFunctions;
7-
private int [] bitArray;
9+
private BitSet bitArray;
810
private Hash<T>[] hashFunctions;
911

1012
public BloomFilter(int numberOfHashFunctions, int n) {
1113
this.numberOfHashFunctions = numberOfHashFunctions;
1214
hashFunctions = new Hash[numberOfHashFunctions];
13-
bitArray = new int[n];
15+
bitArray = new BitSet(n);
1416
insertHash();
1517
}
1618

@@ -22,13 +24,15 @@ private void insertHash() {
2224

2325
public void insert(T key) {
2426
for (Hash<T> hash : hashFunctions){
25-
bitArray[hash.compute(key) % bitArray.length] = 1;
27+
int position = hash.compute(key) % bitArray.size();
28+
bitArray.set(position);
2629
}
2730
}
2831

2932
public boolean contains(T key) {
3033
for (Hash<T> hash : hashFunctions){
31-
if (bitArray[hash.compute(key) % bitArray.length] == 0){
34+
int position = hash.compute(key) % bitArray.size();
35+
if (!bitArray.get(position)) {
3236
return false;
3337
}
3438
}

0 commit comments

Comments
 (0)