Hello,
Datatype: Dictionary keys
Can somebody please tell me importance of implementing both(hashCode/equals) of them simultaneously. because I think if we implement hashCode method equals is going to compare hashCodes and give us the equality.
Hello,
Datatype: Dictionary keys
Can somebody please tell me importance of implementing both(hashCode/equals) of them simultaneously. because I think if we implement hashCode method equals is going to compare hashCodes and give us the equality.
Just because hash codes are equal does not mean that the underlying objects are equal. There are a limited number of possible hash codes, so there are bound to be collisions. You should implement a robust .Equals()
so that you can actually test for equality.
A HashCode does not guarantee uniqueness. As an example, a HashCode takes 2^32 values in most languages. If you have a class of 4 ints, how many possible unique states/instances of that class could you have? (2^32)^4. Meaning even if you implement a perfect hashcode, you would still have 2^(32*3) collisions, where a pair of different objects have the same hashcode.
The HashCode is therefore used as a first 'fast' comparison, to find objects that look similar to what you are looking for. Once you get down to a group of objects, equality is checked on each to see if there is one which is precisely what you are looking for.
The problem is that just because two objects have the same hashcode doesn't mean that they're equal.
There are only 2^32 possible hash codes (32-bit integers). If you think about it, you'll realize that the number of possible strings is much much much larger. Therefore, not every string will have a unique hashcode.
Also, many classes' GetHashCode
methods are poorly implemented.
For example, here is Point.GetHashCode
from the .Net source code:
public override int GetHashCode() {
return x ^ y;
}
Notice that (2, 3)
will have the same hashcode as (3, 2)
, even though they're not equal. Although there are implementations that do not exhibit this behavior, they're still, by definition, not unique.