Reputation: 445
Dictionary
in C# uses GetHashCode() to retrieve hash code of a given key. I walk through whole of the Dictionary Class
, but there is not any definition for GetHashCode()
function. It is bothering me and I don't know how I can find definition of it in this class!
Assume I am using Dictionary<int,int> a = new Dictionary<int,int>()
, now what is the hash code of a given key in this structure? (e.g. suppose this: a.Add(123,43)
. what is the hash code of this key, if number of buckets being 50)
This is a part of Insert()
function of Dictionary class
.
private void Insert(TKey key, TValue value, bool add)
{
int freeList;
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (this.buckets == null)
{
this.Initialize(0);
}
int num = this.comparer.GetHashCode(key) & 0x7fffffff;
int index = num % this.buckets.Length;
Upvotes: 0
Views: 323
Reputation: 171178
If you don't specify an IEqualityComparer
, Dictionary
uses EqualityComparer<T>.Default
. This is a comparer that will just call object.GetHashCode
on the given argument. So look at Int32.GetHashCode
.
Upvotes: 3
Reputation: 125620
GetHashCode
is implemented on your TKey
type, not on the Dictionary
class.
For int.GetHashCode()
, which your example uses, it's defined as:
public override int GetHashCode()
{
return this;
}
Number of backets has nothing to do with the hashcode value.
Upvotes: 2