Skip to content

Commit 65dd4d9

Browse files
committed
fix(bloomfilter): hash arrays by content to satisfy array membership tests
1 parent 8e5e111 commit 65dd4d9

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

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

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.thealgorithms.datastructures.bloomfilter;
22

3+
import java.util.Arrays;
34
import java.util.BitSet;
45

56
/**
@@ -115,7 +116,7 @@ private static class Hash<T> {
115116
* @return the computed hash value
116117
*/
117118
public int compute(T key) {
118-
return index * asciiString(String.valueOf(key));
119+
return index * contentHash(key);
119120
}
120121

121122
/**
@@ -135,5 +136,31 @@ private int asciiString(String word) {
135136
}
136137
return sum;
137138
}
139+
140+
/**
141+
* Computes a content-based hash for arrays; falls back to ASCII-sum of String value otherwise.
142+
*/
143+
private int contentHash(Object key) {
144+
if (key instanceof int[]) {
145+
return Arrays.hashCode((int[]) key);
146+
} else if (key instanceof long[]) {
147+
return Arrays.hashCode((long[]) key);
148+
} else if (key instanceof byte[]) {
149+
return Arrays.hashCode((byte[]) key);
150+
} else if (key instanceof short[]) {
151+
return Arrays.hashCode((short[]) key);
152+
} else if (key instanceof char[]) {
153+
return Arrays.hashCode((char[]) key);
154+
} else if (key instanceof boolean[]) {
155+
return Arrays.hashCode((boolean[]) key);
156+
} else if (key instanceof float[]) {
157+
return Arrays.hashCode((float[]) key);
158+
} else if (key instanceof double[]) {
159+
return Arrays.hashCode((double[]) key);
160+
} else if (key instanceof Object[]) {
161+
return Arrays.deepHashCode((Object[]) key);
162+
}
163+
return asciiString(String.valueOf(key));
164+
}
138165
}
139166
}

0 commit comments

Comments
 (0)