Follow general conventions When overriding equals--effective Java reading notes

Source: Internet
Author: User

This is the desired result if any of the following conditions are met:
Each instance of a class is inherently unique.
Does not care if the class provides a "logical equality" test function.
The superclass has overridden equals, and the behavior inherited from the superclass is also appropriate for subclasses.
Class is private or package-level private, it can be determined that its Equals method is never called.

If a class has its own unique "Roggi" concept (unlike the concept of object equivalence), and the superclass does not overwrite equals to achieve the desired behavior, then we need to overwrite the Equals method.

The Equals method implements the equivalence relationship:
Reflexive nature
Symmetry of
Transitivity
Consistency
Non-nullability: x,x.equals (NULL) must return FALSE for any non-null reference value

Tips for implementing the high-quality equals method:
1. Use the = = operator to check if the parameter is a reference to this object.
2. Use the instanceof operator to check if the parameter is the correct type.
3. Convert the parameters to the correct type.
4. For each "critical" field in the class, check that the field in the parameter matches the field in the object.
5. When you have written the Equals method, you should ask yourself three questions: Is it symmetric, transitive, and consistent?

Warned:
Always overwrite hashcode when you overwrite equals.
Do not attempt to make the Equals method too intelligent.
Do not replace object objects in the equals declaration with other types.

Follow general conventions When overriding equals--effective Java reading notes

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.