I’m trying to implement a dictionary with a hash table (not using Java’s provided hash table classes, but rather made from scratch). Below is the insert() method from my Dictionary class, used to insert an element into a linked list contained in the particular array position.
I am running a supplied test program to determine if my Dictionary class works, but I am encountering a ArrayIndexOutOfBoundsException: -5980 when reaching a certain point. Included below is the particular test. Why would this exception be coming up? (I can provide more code if needed!)
Insert:
public int insert(DictEntry pair) throws DictionaryException {
String entryConfig = pair.getConfig();
int found = find(entryConfig);
if (found != -1) {
throw new DictionaryException("Pair already in dictionary.");
}
int entryPosition = hash(entryConfig);
if (dict[entryPosition] == null) { //Dictionary.java:54
LinkedList<DictEntry> list = new LinkedList<DictEntry>();
dict[entryPosition] = list;
list.add(pair);
return 0;
} else {
LinkedList<DictEntry> list = dict[entryPosition];
list.addLast(pair);
return 1;
}
}
The test:
// Test 7: insert 10000 different values into the Dictionary
// NOTE: Dictionary is of size 9901
try {
for (int i = 0; i < 10000; ++i) {
s = (new Integer(i)).toString();
for (int j = 0; j < 5; ++j) s += s;
collisions += dict.insert(new DictEntry(s,i)); //TestDict.java:69
}
System.out.println(" Test 7 succeeded");
} catch (DictionaryException e) {
System.out.println("***Test 7 failed");
}
Exception stack trace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -5980
at Dictionary.insert(Dictionary.java:54)
at TestDict.main(TestDict.java:69)
Hash function:
private int hash(String config) {
int expBase = 41;
int exp;
int ASCIIChar;
int hashedConfig = 0;
for (int i = 0; i < config.length(); i++) {
ASCIIChar = (int)config.charAt(i);
exp = (int)Math.pow(expBase, i);
hashedConfig = hashedConfig + (ASCIIChar * exp);
}
hashedConfig = hashedConfig % dictSize;
return hashedConfig;
}
Your
will overflow integer range, therefore generate negative numbers. Add a
Math.absbefore returning hashedConfig.You probably should do an analysis how this affects the distribution of your hash function.