Answer the question
In order to leave comments, you need to log in
Contract equals and hashCode?
Hello, I understand that this question is quite popular and can be easily searched on the Internet, but I met different information on different sources, so for me as a beginner, this is confusing.
Here is my understanding of how these two methods work.
In order to compare objects correctly, we need to redefine both equals and hashCode, since without redefinition, implementations of these methods of the Object class will be used, which in most cases is not suitable.
We want to find out if the objects are equal by comparing the fields of the objects, for example id. When adding two objects as a key to the same HashMap, hashCode will be called first, since it seems to make a simple mathematical calculation using a formula faster than comparing using equals (but this is not accurate).
If hashCode returns different numbers for those objects, then the objects are guaranteed to be different. If the hash codes are equal, then the slow equals method is called, since in this case the equality of the hash codes does not guarantee that the objects are equal (collision, due to the fact that there can be an infinite number of combinations of these objects, and the number of hash combinations codes is limited to the range of int).
Accordingly, equals is guaranteed to correctly compare objects, even if the hashCode of two objects is the same.
Those. different hash codes indicate that the objects are different, but if the hash codes match, then we additionally check using equals. That. equals may return false even if the hash codes match.
Or is it first compared through equals (as they say in many sources)?
Answer the question
In order to leave comments, you need to log in
since it seems to do a simple mathematical calculation using a formula is faster than comparing using equals (but this is not accurate)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question