Skip to content

Commit 840fc9b

Browse files
committed
Add Unit Test for Handling Negative Hash Codes in Custom HashTable Implementation
This commit introduces a new unit test and a supporting class to validate the handling of negative hash codes within our custom HashTable implementation. Changes: Unit Test: Test_NegativeHashKey_ReturnsCorrectValue Purpose: The test ensures that the HashTable correctly handles keys with negative hash codes. This scenario is important for robustness, as real-world use cases might involve hash codes that are negative, especially when custom GetHashCode implementations are involved. Implementation: A new HashTable is instantiated with a small initial capacity (4) to ensure hash collisions and proper management of entries. The test adds a key-value pair to the HashTable where the key (NegativeHashKey) intentionally generates a negative hash code. The test then asserts that the value can be correctly retrieved using a key that generates the same negative hash code, verifying the integrity of the HashTable under these conditions. Supporting Class: NegativeHashKey Purpose: The NegativeHashKey class is designed to simulate keys that produce negative hash codes, which is essential for triggering the edge case being tested. Implementation: The class contains an integer id used to generate a negative hash code by returning the negation of id in the GetHashCode method. The Equals method is overridden to ensure correct key comparison based on the id field, allowing the HashTable to manage and compare instances of NegativeHashKey accurately.
1 parent 9eb2196 commit 840fc9b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

DataStructures.Tests/Hashing/HashTableTests.cs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,4 +381,37 @@ public void This_Get_KeyNotFoundException_WhenKeyDoesNotExist()
381381
Console.WriteLine(value);
382382
});
383383
}
384+
385+
[Test]
386+
public void Test_NegativeHashKey_ReturnsCorrectValue()
387+
{
388+
var hashTable = new HashTable<NegativeHashKey, int>(4);
389+
hashTable.Add(new NegativeHashKey(1), 1);
390+
Assert.That(hashTable[new NegativeHashKey(1)], Is.EqualTo(1));
391+
}
392+
}
393+
394+
public class NegativeHashKey
395+
{
396+
private readonly int id;
397+
398+
public NegativeHashKey(int id)
399+
{
400+
this.id = id;
401+
}
402+
403+
public override int GetHashCode()
404+
{
405+
// Return a negative hash code
406+
return -id;
407+
}
408+
409+
public override bool Equals(object? obj)
410+
{
411+
if (obj is NegativeHashKey other)
412+
{
413+
return id == other.id;
414+
}
415+
return false;
416+
}
384417
}

0 commit comments

Comments
 (0)