Same GetHashCode() for different objects

2020-04-27 05:23发布

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?

标签: c# .net hashcode
4条回答
男人必须洒脱
2楼-- · 2020-04-27 05:28

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.

查看更多
Anthone
3楼-- · 2020-04-27 05:33

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.

查看更多
成全新的幸福
4楼-- · 2020-04-27 05:33

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.

查看更多
▲ chillily
5楼-- · 2020-04-27 05:34

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.

查看更多
登录 后发表回答