views:

134

answers:

2

Hi all,

As I know, in HashTable the key string's hash value is unique because if there are two same strings, the GetHashCode() function will overwrite the first one with the second.

This will ensure that there's no identical hash values generated by the different strings with same values.

But when it comes to generic dictionary class, we can specify any type as the type parameter for the key.

So, the hash value generated by that key can't be unique since it does not perform the string behaviour. Is that so?

If not, what is the procedure going behind this generic scenario?

Thanks in advance,

Jay...

+2  A: 

The hash is only used to put items into 'buckets' for the purposes of quick lookup. The hash value isn't used for determining equality.

So don't worry, if two strings (or whatever) return the exact same hash, they'll indeed go into the same bucket, but they'll still be separate 'keys'.

Chris
+1  A: 

The hash value is obtained by GetHashCode(), which every object implements. The default implementation, inherited from System.Object, does not guarantee unique return values for different objects.

However, hash values do not need to be unique to the object, since they're only used to speed up searching, and your key class still needs an equality implementation to determine whether keys are equal.

So if you use System.Object as your key, it will know one key from another based on the equality of the reference, as it will use Object.Equals to figure that out.

Dave Van den Eynde