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.