Rewrite the rules of the equlas () method

Source: Internet
Author: User

The equals method implements the equivalence relationship. Generally, the following conditions must be met:

Reflexive)

Symmetry)

Transitive)

Consistent)

For any non-null reference value X, X. Equals (null) must return false.

To implement a high-quality equals method, you can do the following:

Use the = Operator to check whether the real parameter is a reference to the object. If yes, return true;

Use the instanceof operator to check whether the real parameter is of the correct type ",

If not, false is returned;

Convert real parameters to the correct type

For each "significant" field in the class, check whether the field in the real parameter matches the Domain value in the current object.

True is returned if all tests are successful;

For example:

Class programer {
Int number;
Public programer (int n ){
Number = N;
}
// The hashcode () method must be overwritten.
Public int hashcode (){
Return number;
}
Public Boolean equals (Object OBJ ){
If (this = OBJ) return true; // compare whether the references of two objects are equal
If (OBJ = NULL) return false; // check if obj is null
If (! (OBJ instanceof (programer) return false;
Return (number = (programer) OBJ). number );
}
}

After the equals method is compiled, it should satisfy the following requirements: Is it symmetric, transmitted, and consistent?
  
Note:

1) When you rewrite equals, you always need to rewrite the hascode method.

2) do not replace the object in the equals declaration with another type.

When your equals does not work properly, check if you have made the following mistakes.

Public Boolean equals (myclass O ){

...

}
This method is not an equals method that overwrites the object class.

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.