If hashcodes of two object is same, objects are equals?whats mechanism in equals? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

If hashcodes of two object is same, objects are equals?whats mechanism in equals?

14th Sep 2018, 8:28 PM
Mohammad Askari
Mohammad Askari - avatar
2 Answers
+ 3
In general YES but there's a catch. In fact, the number of possible hash output (fixed-length) is much smaller (infinite) than the input and hence it's possible to have same hash for two differrent objects. However, if strong hash algorithm was used then the probability to find a match for scenario above is negligible so it's safe to assume same hash means same object. 😉
14th Sep 2018, 11:56 PM
Zephyr Koo
Zephyr Koo - avatar
+ 1
By default, if you are creating new classes, equals() will just look at object references i.e is this the same object in memory. This is often not useful, so most of the in-built types have equals() methods that compare other things, like class fields. In good class design, if two objects are considered equal (by equals() method) then their hashcodes should also be equal. However, it is NOT a requirement that two objects with equal hashcodes be equal according to equals(), so it's not an equivalence. (of course, you could have bad design and make the hashCode method always return 0 or something, without affecting how equals() behaves) The jdk source code is viewable online so is quite easy to find how equals() is implemented for various classes
15th Sep 2018, 2:10 AM
Dan Walker
Dan Walker - avatar