Role of hashcode

Source: Internet
Author: User

If you want to save an object to a hash collection (such as a hashset), you can determine whether the object is the same Based on the hashcode of the object, generally, the hashcode is calculated based on the object address by default, and the equals method determines whether the two object addresses are equal by default. Therefore, if the equals method is not rewritten, The hashcode method is not rewritten, if the equals method is rewritten to make the two different address objects equals true, the hashcode must be rewritten to make their hashcode equally.

Why? Because if you want to save an object to a hashset, if the two objects equals are true, It should be saved as one. However, if the hashcode is different, both objects are saved in this situation, so we need to rewrite the hashcode to the same one.

Note that if you rewrite the hashcode method of the object, do not change the attribute variable used to calculate the hashcode value in the object after saving the object into the hashset, this will change the hashcode value of this object, and may cause the hashset to no longer operate on this object, resulting in Memory leakage !!

Role of hashcode

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.