Skip to content

Commit

Permalink
Fixed collision bug in HashTable
Browse files Browse the repository at this point in the history
  • Loading branch information
jrasmusson committed Jan 18, 2020
1 parent 874e393 commit d0584dc
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 12 deletions.
20 changes: 8 additions & 12 deletions src/main/java/datastructures/HashTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,14 @@ public String get(String key) {
// Get the current list of entries
HashEntry entries = data[index];

// if we have existing entries against this key...
if (entries != null) {
// else walk chain until find a match
while (!entries.key.equals(key) && entries.next !=null) {
entries = entries.next;
}
// then return it
return entries.value;
// While there are elements in the linked list...
while (entries != null) {
if (entries.key.equals(key)) // Check for match
return entries.value; // if match found return
entries = entries.next; // else go to next node in chain
}

// it we have no entries against this key...
return null;
return null; // return null if no match found
}

private int getIndex(String key) {
Expand All @@ -75,8 +71,8 @@ private int getIndex(String key) {
int index = (hashCode & 0x7fffffff) % INITIAL_SIZE;

// Hack to force collision for testing
if (key.equals("John Smith") || key.equals("Sandra Dee")) {
index = 7; // 4 clashes with other names (changed to 7)
if (key.equals("John Smith") || key.equals("Sandra Dee") || key.equals("Tim Lee")) {
index = 4;
}

return index;
Expand Down
1 change: 1 addition & 0 deletions src/test/java/datastructures/HashTableTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public void PutAndGet() {

@Test
public void Empty() {
Assert.assertEquals(null, hashTable.get("Ted Baker"));
Assert.assertEquals(null, hashTable.get("Tim Lee"));
hashTable.toString();
}
Expand Down

0 comments on commit d0584dc

Please sign in to comment.