From ec1ab53eeacbd9913206bb5ab98c1dd7dfe2ebbe Mon Sep 17 00:00:00 2001 From: Artem Boiarshinov <54187376+Boiarshinov@users.noreply.github.com> Date: Fri, 10 Jun 2022 20:44:23 +0300 Subject: [PATCH] Reduce memory usage of bloom filter (#3115) --- .../datastructures/bloomfilter/BloomFilter.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java b/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java index ed77bb3c6..71ad0e42f 100644 --- a/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java +++ b/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java @@ -1,16 +1,18 @@ package com.thealgorithms.datastructures.bloomfilter; +import java.util.BitSet; + public class BloomFilter { private int numberOfHashFunctions; - private int [] bitArray; + private BitSet bitArray; private Hash[] hashFunctions; public BloomFilter(int numberOfHashFunctions, int n) { this.numberOfHashFunctions = numberOfHashFunctions; hashFunctions = new Hash[numberOfHashFunctions]; - bitArray = new int[n]; + bitArray = new BitSet(n); insertHash(); } @@ -22,13 +24,15 @@ public class BloomFilter { public void insert(T key) { for (Hash hash : hashFunctions){ - bitArray[hash.compute(key) % bitArray.length] = 1; + int position = hash.compute(key) % bitArray.size(); + bitArray.set(position); } } public boolean contains(T key) { for (Hash hash : hashFunctions){ - if (bitArray[hash.compute(key) % bitArray.length] == 0){ + int position = hash.compute(key) % bitArray.size(); + if (!bitArray.get(position)) { return false; } }