Compare this object with the specified object. If and only if the parameter is not
nullAnd the object contains the same
intValue
IntegerObject, the result is
true. (Note: only compare the values and do not compare whether the references are the same)
For example, the following two objects animal1 and animal reference different objects, so the result of comparison with = or equals () is false, while the animal1 and animal variables reference the same dog object, therefore, the result of comparison with = or equals () is true.
Animal animal1 = new dog ();
Animal animal = new CAT ();
Animal anim_3 = animal1;
Then animal1 = animal (false)
Animal1.equals (animal) (false)
Animal1 = anim_3 (true)
Animal1.equals (anim_3) (true)
Some classes in the JDK class overwrite the equals () method of the oject class. The comparison rule is: if the two objects have the same type and the content is consistent, true is returned. These classes include:
Java. Io. File, java. util. Date, java. Lang. String, packaging class (integer, double, etc)
For example
Integer int1 = new INTEGER (1 );
Integer int2 = new INTEGER (1 );
String str1 = new string ("hello ");
String str2 = new string ("hello ");
Int1 = int2 output: false, because different objects // because int1, int2 represents object reference, their values are memory addresses
Int1.equals (int2) Output: True // integer overwrites the equals method of the object and only compares the values in the object.
Str1 = str2 (false)
Str1.equals (str2) (true)
Of course, you can customize the equals () method that overwrites the object class and redefine the comparison rules. For example, the following equals () Comparison rule for the person class is as follows: if both objects are person classes and their attribute names are the same, the comparison result is true; otherwise, false is returned.
Public class person {
Private string name;
Public Person (string name)
{
This. Name = Name;
}
Public Boolean equals (Object O)
{
If (this = 0) return true;
If (! O instanceof person) return false;
Final Person Other = (person) O;
If (this. Name (). Equals (other. Name ()))
Return true;
Else
Return false;
}
}
Note: When rewriting the equals method, you must satisfy the Discrete Mathematical characteristics.
1. Self-inverse: the return value of X and X. Equals (x) must be true.
2 symmetry: For any referenced values X and Y, if and only when Y. Equals (x) returns true, the return value of X. Equals (y) must be true;
3 pass: If X. Equals (y) = true, Y. Equals (z) = true, X. Equals (z) = true
4. Consistency: If the objects involved in the comparison are not changed, the results of the object comparison should not be changed.
5. non-null: the return value of any non-null reference values X and X. Equals (null) must be false.