What are precautions for implementing java. Lang. Object. Equals (object?

Source: Internet
Author: User

If all objects in the world are judged by direct equals, it will be okay. There are always some situations:

  • Objects are placed in containers (such as hashset), and then equals is judged;
  • Perform equals judgment between the object and the subclass of the inherited object;
  • ......

 

[1] an incorrect equals method signature is defined.

No: Public Boolean euqals (pointer O );

Yes: Public Boolean equals (ObjectO );

 

[2] The equals method is reloaded, but the hashcode method is not reloaded at the same time.

No: No hashcode ()

Yes: Public intHashcode (){Return (41*(41 + getx () + Gety ());}

 

[3] equals definition based on changing word Fields

No: Public int;

Yes: PublicFinalInt;

 

[4] equals error definitions that do not meet the equivalence relationship

No: direct parent and sub-object comparison;

Yes: & this.Getclass ().Equals (that. getclass ())

 

 

Learning:

Http://blog.csdn.net/haoel/article/details/4282239

Http://www.artima.com/lejava/articles/equality.html

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.