0

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.

Denis
  • 664
  • 9
  • 24
  • Can you give a minimal but complete example that reproduces your problem? – Jeroen Vannevel Jan 10 '16 at 18:15
  • The documentation on `GetHashCode` mentions "do not use the default implementation of this method as a unique object identifier for hashing purposes" (see https://msdn.microsoft.com/en-us/library/system.object.gethashcode(v=vs.110).aspx) – C.Evenhuis Jan 10 '16 at 18:18
  • 2
    There is no obligation for GetHashCode() to "encrypt" the value. If K is *int* for example then, yes, you get the same value back. A perfect hash, highly desirable. – Hans Passant Jan 10 '16 at 18:30
  • I see. This means that if I want to get a hash function which better distributes load (more random), I'd need to implement my own override, probably using a simple encryptor and getting the modulo of it. – Denis Jan 10 '16 at 19:32

1 Answers1

1

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?

Community
  • 1
  • 1
Guy Levy
  • 1,550
  • 2
  • 15
  • 26