First off, this is a homework assignment. I am having some difficulty adding a new item to the HashTable when a collision occurs. We can only use the basic utilities to code this, so we are coding a HashTable by hand. We have an array of length of 10, which each index holds or will hold a Node for a Linked List.
The code hashes fine, adds the item, but the problem exists when adding items that already been hashed. The project is much bigger, but this is the engine behind the rest, and I figured I would tackle this first.
The items we are adding are objects which are states containing different information, we hash based on the ASCII sum % tableSize.
Here is the code I am testing with to add items:
HashTable ht = new HashTable(10);
State az = new State("Arizona","AZ","W",2,"Y",2);
State fl = new State("Florida", "FL", "F", 2, "X", 2);
State hi = new State("Hawaii", "HI", "H", 3, "Z", 1);
State al = new State("Alabama", "AL", "A", 5, "W", 0);
ht.insert(hi);
ht.insert(az);
ht.insert(al);
ht.insert(fl);
ht.insert(hi);
ht.insert(fl);
ht.display();
ht.insert2(fl);
}
Here is the insertion method:
public void insert(State state) {
int hash = getHash(state.getName());
Node n = new Node(state);
Node temp = hashTable[hash];
if (isEmpty(hash)) { // Check to see if the hashed index of the array is empty
hashTable[hash] = n;
} else if (n.getState().getName().compareTo(temp.getState().getName()) <= 0) {
n.setNext(temp.getNext());
temp.setNext(n);
} else {
n.setNext(temp);
hashTable[hash] = n;
}
}
Appreciate any help!

New Topic/Question
Reply


MultiQuote



|