Search code examples
c#hashtablegethashcode

key.GetHashCode() returns key


I am implementing a hashtable and I use GetHashCode to get a unique hashcode for each key I'm using, however, when I call key.GetHashCode(), the function returns the key. After I use the modulo to get the right bucket of the hashtable, we are able to implement the hashtable but this does not look right.

Here is how I call it.

public V Find(K key)
    {
        int bucketIndex = key.GetHashCode() % N;
        return buckets[bucketIndex].Find(key);
    }

Is there special initialization we're supposed to do before calling gethashcode?

I'm now thinking of writing my own hash function in an overloaded function but think it'd be easier to use the function call.


Solution

  • There is no "special initialization" to do before calling GetHashCode(). As Hans wrote, GetHashCode() of Int32 will return the int itself (see this answer).

    The default implementation of GetHashCode() does not guarantee uniqueness. To reduce hash code collision, you need to overwrite the method. There is a popular generic suggestion for GetHashCode() here: What is the best algorithm for an overridden System.Object.GetHashCode?