开发者

Why, If two objects are not equal according to equals, they are not required to return different hashCode values? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

In Java, why must equals() and hashCode() be consistent?

Why hashCode() can return the same value for different objects in java?

In JAVA API we can see that

If two objects are not equal according to equals, they are not required to return different hashCode values.

Why is it so?

If two objects are not equal according 开发者_JAVA百科to equals, then it should be required to return different hashCode values right?


Hash code is AFAIR a 32-bit integer, so a number of states is limited to 2^32. Almost every class you create will have a much bigger number of possible states, so it is impossible to ensure that different objects will not have the same hashcode value.

Inequality of hashcodes means that objects are not equal, however equality of hashcodes means that objects may be equal.


The reason is basically because the hashCode is not the same as the Equals code. That's why you have the equals().

The hascode can (and will) have collisions. You have somthing with information worth X bits, but you code it in a hash that has less then X bits (cutting some corners here). So therefore some duplicates MUST be available for non-equal objects.


They are not required to return different hashcodes, but if they do, all the hash related Java algorithms will perform better because there will be fewer hash collisions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜