import java.util.BitSet;
public class BloomFilter {
private static int defaultSize = 2 << 24;
private static int basic = defaultSize - 1;
private static BitSet bits;
private static BloomFilter bf = new BloomFilter();
public BloomFilter() {
bits = new BitSet(defaultSize);
}
public static boolean contains(String url) {
if (url == null) {
return true;
}
int pos1 = hash1(url);
int pos2 = hash2(url);
int pos3 = hash3(url);
if (bits.get(pos1) && bits.get(pos2) && bits.get(pos3)) {
return true;
}
return false;
}
public static void add(String url) {
if (url == null) {
return;
}
int pos1 = hash1(url);
int pos2 = hash2(url);
int pos3 = hash3(url);
bits.set(pos1);
bits.set(pos2);
bits.set(pos3);
}
private static int hash3(String line) {
int h = 0;
int len = line.length();
for (int i = 0; i < len; i++) {
h = 37 * h + line.charAt(i);
}
return check(h);
}
private static int hash2(String line) {
int h = 0;
int len = line.length();
for (int i = 0; i < len; i++) {
h = 33 * h + line.charAt(i);
}
return check(h);
}
private static int hash1(String line) {
int h = 0;
int len = line.length();
for (int i = 0; i < len; i++) {
h = 31 * h + line.charAt(i);
}
return check(h);
}
private static int check(int h) {
return basic & h;
}
}