How does the Hashcode () method work in Java?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.