Proposal to write a perfect Equals method (Java)

Source: Internet
Author: User

1. The display parameter is named Otherobject and later it needs to be converted to another variable called other.

2. Detect if this and otherobject refer to the same object:

if (This==otherobject) return true;

This statement is just an optimization. In fact, this is a frequently used form of amount. Because it is much less expensive to calculate the lighting than to compare the fields in the class one by one.

3. Detects if Otherobject is null, and returns FALSE if null. This test is very necessary.

if (otherobject==null) return false;

4. Compare whether this and otherobject enter the same class. If the semantics of equals are changed in each subclass, use Geiclass to detect

if (GetClass ()!=otherobject.getclass ()) return false;

If all the self-thunder have unified semantics, use instanceof detection

if (! ( Otherobject instanceof ClassName)) return false;

5 converting Otherobject to the appropriate class-type variable

ClassName other = (ClassName) otherobject;

6. Now it's time to compare all the fields that need to be compared. Use = = to compare the base type fields, using equals to compare object fields. Returns True if all the fields match. Otherwise, false is returned.

Return field1==other.field1&& objects.equals (field2,other.field2) &.....;

If you redefine equals in a subclass, you must include the call Super.equals (other)

Tips: For arrays of type fields, you can use the static Arrays.equals method to detect if the corresponding array elements are equal

Proposal to write a perfect Equals method (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.