简体   繁体   中英

Definition of GetHashCode() in C#

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? (eg 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;

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM