I'm implementing hash table using generics, like Dictionary implemented in c#, but I'm stuck in Hash function part. I successufuly rewritten non-generic implementation of Hash table in generic one but you will notice in code that I have no idea how to hash Tkey.
class Node<T, U>
{
public T key;
public U value;
public Node<T, U> next;
public Node(T key, U value, Node<T, U> next)
{
this.key = key;
this.value = value;
this.next = next;
}
}
public class HashTable<T,U>
{
int length;
Node<T,U>[] buckets;
public HashTable(int length)
{
this.length = length;
buckets = new Node<T,U>[length];
}
public void Display()
{
for (int bucket = 0; bucket<buckets.Length; bucket++)
{
Node<T,U> current = buckets[bucket];
Console.Write(bucket + ":");
while (current != null)
{
Console.Write("["+current.key+","+current.value+"]");
current=current.next;
}
Console.WriteLine();
}
}
// private int Hash(T Tkey) ...
//// non-generic version of hash function
private int Hash(string str)
{
int h=0;
foreach(var s in str)
h=127*h+s;
return h%length;
}
////
public void Insert(T key, U value)
{
int bucket = Hash(key);
buckets[bucket] = new Node<T,U>(key, value, buckets[bucket]);
}
public U Search(T key)
{
Node<T,U> current = buckets[Hash(key)];
while (current != null)
{
if (current.key.Equals(key))
return current.value;
current= current.next;
}
throw new Exception(key+ "Not found");
}