GetHashCode()
returns a int32
as hash.
I was wondering how would it work when the number of elements exceed int.MaxValue
, as all of them would have returned some integer <= int.MaxValue
?
GetHashCode()
returns a int32
as hash.
I was wondering how would it work when the number of elements exceed int.MaxValue
, as all of them would have returned some integer <= int.MaxValue
?
There is no requirement that if object1.GetHashCode() == object2.GetHashCode()
, then object1.Equals(object2)
. Any container type that uses hash codes must be prepared to deal with hash collisions. One possible way to do that is to store all different objects with the same hash code in a list, and when looking up an object, first look up the hash code, and then iterate over the objects in the associated list, calling Equals
for every object until you find a match.
As already mentioned, GetHashCode does not produce unique results.
A dictionary stores at each location a keyvaluepair, so when collisions occur, the items with the same hashcode (modded to the size of the underlying array) are chained and the actual key you are looking to retrieve is searched for.
A Dictionary is O(1) in its best case, and even average case, but at worst case, it is O(n).