问题
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?
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
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:
- If two objects are equal, they should have the same hash code.
- 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.
来源:https://stackoverflow.com/questions/26615134/same-gethashcode-for-different-objects