Dictionary class key value

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

This ensures that there are no identical hash values ​​generated by different strings with the same values.

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

Thus, the hash value generated by this key cannot be unique as it does not enforce string behavior. This is true?

If not, what is the procedure followed for this common scenario?

Thanks in advance,

Jay ...

+1


a source to share


2 answers


The hash is only used to send items to buckets for quick searches. The hash value is not used to determine equality.



So don't worry if two strings (or something else) return the same hash, they will indeed go into the same bucket, but they will still be separate "keys".

+3


a source


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

However, the hash values ​​do not have to be unique to the object, as they are only used to speed up lookups, and your class still needs an equality implementation to determine if keys are equal.



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

+1


a source







All Articles