Hashcode This method is used to identify whether 2 objects are equal.
So you're going to say, isn't that the Equals method?
Yes, these 2 methods are used to determine whether 2 objects are equal. But they are different.
In general, the Equals method is called to the user, if you want to determine whether 2 objects are equal, you can rewrite the Equals method and then call in the code to determine whether they are equal. In simple terms, the Equals method is primarily used to judge whether 2 objects are not equal on the surface or on the content. For example, there is a student class, the attribute is only the name and gender, then we can think that as long as the name and gender equality, then say that the 2 objects are equal.
Hashcode method General users do not call, such as in HashMap, because key is not repeatable, he in the judgment key is not repeated when the hashcode this method, but also used the Equals method. Here can not repeat is that equals and hashcode as long as there is a range! So simply put, hashcode is equivalent to an object encoding, as if the file of MD5, he and equals is the difference is that he returned to the int type, compared to not intuitive. We generally overwrite equals while covering the hashcode to make their logic consistent. For example, if the name and gender are equal even if 2 objects are equal, then the Hashcode method also returns the Hashcode value of the name plus the hashcode value of the gender, so logically they are consistent.
To physically determine whether 2 objects are equal, use = = to
Hashcode () is explicitly used in methods where hash functions be used, like hashTable () etc.
One should always override Hashcode () when overriding equals (). Unexpected behaviour would occur if you don ' t.
Hashcode () should has the same value whenever equals () returns True.
How does the Hashcode () method work in Java?