0

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?

Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
  • What is so special about `int.MaxValue`? Can you think of an issue that appears which does not also appear for a much smaller number of elements, e.g. 1000? – Jon Feb 26 '14 at 11:29
  • A bad, but legal implementation of `GetHashCode` for any particular type of object is `return 0;`. Every object can have the same hash code. This makes the algorithms that try to use it inefficient, but the universe carries on working. – Damien_The_Unbeliever Feb 26 '14 at 11:39

2 Answers2

0

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.

0

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).

David
  • 1,754
  • 23
  • 35