Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equal Objects must have equal hashcodes?

Equal Objects must have equal hashcodes. As per my understanding this statement is valid when we have intention of using object in hashbased datastuctures. This is one of contract for hashcode and equals method in java docs. I explored the reason why this is said and looked in the implementation of hashtable and found out below code in put method

if ((e.hash == hash) && e.key.equals(key)) 

So I got it, contract came from condition e.hash == hash above. I further tried to explore why java is checking hashcode when comparing two objects for equality. So here is my understaing

  • If two equal object have equal hascodes then they can be stored in the same bucket and this will be good in terms of look up in single bucket only

  • Its better to check hashcode then actually calling equals method because hascode method is less costly than equals method, because here we just have to compare int value where in equals method may be invloving object field comparison. So hashcode method providing one extra filter.

Please correct me if both above reasons are valid?

like image 349
M Sach Avatar asked May 25 '26 04:05

M Sach


1 Answers

  1. Correct, just a small correction - if two unequal objects have the same hashcode.
  2. Not exactly, It's better to check it first, as a filter for the non-equal, but if you want to make sure the objects are equal, you should call equals()
like image 143
MByD Avatar answered May 30 '26 04:05

MByD