From d0584dc706192c54f803b6f027a2ed98286e0099 Mon Sep 17 00:00:00 2001 From: jrasmusson Date: Sat, 18 Jan 2020 05:49:31 -0700 Subject: [PATCH] Fixed collision bug in HashTable --- src/main/java/datastructures/HashTable.java | 20 ++++++++----------- .../java/datastructures/HashTableTest.java | 1 + 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/src/main/java/datastructures/HashTable.java b/src/main/java/datastructures/HashTable.java index 8b5b172..2d3011a 100644 --- a/src/main/java/datastructures/HashTable.java +++ b/src/main/java/datastructures/HashTable.java @@ -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) { @@ -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; diff --git a/src/test/java/datastructures/HashTableTest.java b/src/test/java/datastructures/HashTableTest.java index 39d95ff..d316784 100644 --- a/src/test/java/datastructures/HashTableTest.java +++ b/src/test/java/datastructures/HashTableTest.java @@ -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(); }