For an assignment I have to make a HashTable
using double hashing, but for the hashing part I am not allowed to use Object#hashCode()
, so I have to write my own.
So far I have the following code and I am looking for feedback if I am on the right track or if I should go for a different approach (see hash
and hash2
methods).
public class DoubleHashing<Key, Value> {
private int N;
private int M;
private Key[] keys;
private Value[] vals;
public DoubleHashing(final int capacity) {
M = capacity;
keys = (Key[]) new Object[M];
vals = (Value[]) new Object[M];
}
public int hash(final Key key) {
int hashKey = 0;
if (key instanceof String) {
final String k = (String) key;
for (int i = 0; i < k.length(); i++) {
int charCode = k.charAt(i);
hashKey = ((hashKey * 27) + charCode) % M;
}
}
return hashKey;
}
public int hash2(final Key key) {
int hashKey = 0;
if (key instanceof String) {
final String k = (String) key;
for (int i = 0; i < k.length(); i++) {
int charCode = k.charAt(i);
hashKey = 5 - ((hashKey * 27) + charCode) % 5;
}
}
return hashKey;
}
public void put(final Key key, final Value val) {
if (N == M) {
System.err.println("Table is full");
return;
}
int i;
for (i = hash(key); keys[i] != null; i = (i + 1) % M)
if (keys[i].equals(key)) { vals[i] = val; return; }
keys[i] = key;
vals[i] = val;
N++;
}
public Value get(final Key key) {
for (int i = hash(key); keys[i] != null; i = (i + 1) % M)
if (keys[i].equals(key))
return vals[i];
return null;
}
public int size() {
return N;
}
}