Skip to content

Commit

Permalink
Added fix for hash value clash because of moduls 16 reduces too often…
Browse files Browse the repository at this point in the history
… to index of 4 which lead to index clashes when we didn't want them
  • Loading branch information
jrasmusson committed Jan 17, 2020
1 parent 082f680 commit 874e393
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
6 changes: 1 addition & 5 deletions src/main/java/datastructures/HashTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,19 +70,15 @@ public String get(String key) {
private int getIndex(String key) {
// Get the hash code
int hashCode = key.hashCode();
System.out.println("hashCode = " + hashCode);

// Convert to index
int index = (hashCode & 0x7fffffff) % INITIAL_SIZE;
// int index = hashCode % INITIAL_SIZE;

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

System.out.println("index = " + index);

return index;
}

Expand Down
8 changes: 8 additions & 0 deletions src/test/java/datastructures/HashTableTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,17 @@ public void PutAndGet() {
Assert.assertEquals("521-5030", hashTable.get("Sam Doe"));
Assert.assertEquals("521-9655", hashTable.get("Sandra Dee"));
Assert.assertEquals("418-4165", hashTable.get("Ted Baker"));
Assert.assertEquals(null, hashTable.get("Tim Lee"));

hashTable.toString();
}

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

@Test
public void Collision() {
// these keys will collide
Expand All @@ -38,5 +45,6 @@ public void Collision() {

Assert.assertEquals("521-1234", hashTable.get("John Smith"));
Assert.assertEquals("521-9655", hashTable.get("Sandra Dee"));
Assert.assertEquals(null, hashTable.get("Tim Lee"));
}
}

0 comments on commit 874e393

Please sign in to comment.