简体   繁体   中英

Same GetHashCode() for different objects

After executing this piece of code:

int a = 50;
float b = 50.0f;
Console.WriteLine(a.GetHashCode() == b.GetHashCode());

We get False , which is expected, since we are dealing with different objects, hence we should get different hashes.

However, if we execute this:

int a = 0;
float b = 0.0f;
Console.WriteLine(a.GetHashCode() == b.GetHashCode());

We get True . Both obejcts return the same hash code: 0 .

Why does this happen? Aren't they supposed to return different hashes?

The GetHashCode of System.Int32 works like:

public override int GetHashCode()
{
    return this;
}

Which of course with this being 0 , it will return 0 .

System.Single 's ( float is alias) GetHashCode is:

public unsafe override int GetHashCode()
{
    float num = this;
    if (num == 0f)
    {
        return 0;
    }
    return *(int*)(&num);
}

Like you see, at 0f it will return 0 .

Program used is ILSpy.

From MSDN Documentation :

Two objects that are equal return hash codes that are equal. However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes.

Objects that are conceptually equal are obligated to return the same hashes. Objects that are different are not obligated to return different hashes. That would only be possible if there were less than 2^32 objects that could ever possibly exist. There are more than that. When objects that are different result in the same hash it is called a "collision". A quality hash algorithm minimizes collisions as much as possible, but they can never be removed entirely.

Why should they? Hash codes are a finite set; as many as you can fit in an Int32 . There are many many doubles that will have the same hash code as any given int or any other given double.

Hash codes basically have to follow two simple rules:

  1. If two objects are equal, they should have the same hash code.
  2. If an object does not mutate its internal state then the hash code should remain the same.

Nothing obliges two objects that are not equal to have different hash codes; it is mathematically impossible.

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