I am trying to insert multiple elements into a symbol/hashtable, but I'm keep getting an error ArrayIndexOutOfBoundsException with negative numbers like -4923. While the array size is 10501. So I tried to resolve this error with a if condition, but it looks like it doesn't work or isn't reached. I'm not sure what goes wrong.
public class LinearProbing implements MultiValueSymbolTable<String, Player> {
private int currentSize = 0;
private int capacity, collisionTotal = 0;
private String[] keys;
private Player[] values;
public LinearProbing(int arraySize) {
capacity = arraySize;
keys = new String[capacity];
values = new Player[capacity];
}
....
private int hash(String key) {
return key.hashCode() % capacity;
}
@Override
public void put(String key, Player value) {
if (key == null || value == null) {
return;
}
int hash = hash(key);
while(keys[hash] != null)
{
hash++;
hash = hash % keys.length;
collisionTotal++;
if (hash <= -1 || hash == capacity) {
hash = 0;
}
}
keys[hash] = key;
values[hash] = value;
currentSize++;
}
Instead of using the hashCode() function from Java I wrote my own hash function and this works now.
private int hash(String key) {
char[] s = new char[key.length()];
int hash = 0;
for (int i = 0; i < key.length(); i++) {
hash = s[i] + (capacity * hash);
}
return hash;
}