"Java Basics" overriding equals needs to rewrite hashcode

Source: Internet
Author: User

  Equals in object is used to compare the equality of two objects, in general, when overriding this method, it is often necessary to also rewrite hashcode to maintain the general contract of the Hashcode method, which declares that the equality object must have an equal hash code.

That is: if Obj1.equals (OBJ2) is true, then Obj1.hashcode = = Obj2.hashcode must also be true;

if Obj1.hashcode = = Obj2.hashcode is equal, but the two objects are not necessarily equal;

If you do not override Equlas, then the comparison is whether the reference to the two object is the same memory address, and the purpose of the override is to compare the value of two objects for equality;

Hashcode is a fast access for hashing data, such as using the Hashset/hashmap/hashtable class to store data, based on the hashcode value of the stored object to determine whether the same. So if we rewrite the euqals for an object, it means that as long as the values of the member variables of the object are equal then Euqals equals true, but does not rewrite hashcode, then we are new to the object , When the original object. Equals (New Object) equals True, the hashcode of the two is not the same, resulting in an inconsistent understanding, such as when storing a hash collection (such as set Class), will store two values of the same object, resulting in confusion, therefore, You will also need to rewrite hashcode ().

"Java Basics" overriding equals needs to rewrite 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.