The importance of the Equals method is needless to say, as long as the two objects you want to compare don't want to be the same object, you should implement the Equals method, and let the object compare to the conditions you think are equal. The following content is just API specification, it's not very advanced, but I first listed it here, Because these norms are not really guaranteed to be implemented in fact.
1. For any reference type, O.equals (o) ==true is established.
2. If O.equals (O1) ==true is established, then O1.equals (o) ==true must also be established.
3. If O.equals (O1) ==true was established and O.equals (O2) ==true was established, O1.equals (O2) ==true was established.
4. If the first call to O.equals (O1) ==true established again O and O1 unchanged, any subsequent calls are established.
5.o.equals (NULL) ==true is not established at any time.
The above rules are not the most complete statements, please see the API documentation for details. For the object class, it provides the most rigorous implementation, that is, the Equals method returns true only if it is the same object. That's what people often say about reference comparisons rather than value comparisons. This implementation is strictly no longer practical, so in a specific subclass (relative to object), if we want to compare the value of an object, we must implement our own Equals method.
Let's take a look at the following procedure:
public boolean equals(Object obj)
{
if (obj == null) return false;
if (!(obj instanceof FieldPosition))
return false;
FieldPosition other = (FieldPosition) obj;
if (attribute == null) {
if (other.attribute != null) {
return false;
}
}
else if (!attribute.equals(other.attribute)) {
return false;
}
return (beginIndex == other.beginIndex
&& endIndex == other.endIndex
&& field == other.field);
}
This is the standard implementation of java.text.FieldPosition in JDK, and there seems to be nothing to say. I believe most or most programmers think that this is the right legal equals implementation. After all, it is the JDK API implementation. Let us speak with the facts:
package debug;
import java.text.*;
public class Test {
public static void main(String[] args) {
FieldPosition fp = new FieldPosition(10);
FieldPosition fp1 = new MyTest(10);
System.out.println(fp.equals(fp1));
System.out.println(fp1.equals(fp));
}
}
class MyTest extends FieldPosition{
int x = 10;
public MyTest(int x){
super(x);
this.x = x;
}
public boolean equals(Object o){
if(o==null) return false;
if(!(o instanceof MyTest )) return false;
return ((MyTest)o).x == this.x;
}
}
Run to see what will print:
System.out.println (Fp.equals (FP1)), printing true
System.out.println (Fp1.equals (FP)); Printing flase