The importance of the Java equals method does not need to be repeated. If you want to compare whether two objects are the same, you should implement the equals method so that the objects can be compared using conditions that you think are equal.
The following content is only the API specification, which has no profound significance. But I listed it first because these specifications are not guaranteed in reality.
1. For any reference type, o. equals (o) = true is true.
2. If o. equals (o1) = true is true, o1.equals (o) = true must also be true.
3. If o. equals (o1) = true and o. equals (o2) = true, then
O1.equals (o2) = true is also true.
4. If the first call o. equals (o1) = true is true, any subsequent call will be valid if o and o1 are not changed.
5. o. equals (null) = true is not true at any time.
The above rules are not the most complete statement. For details, see the API documentation. for the Object class, it provides the most rigorous implementation, that is, the equals method returns true only when it is the same Object, that is, the reference comparison that people often say is not the value comparison. this strict implementation has no practical significance, so in the specific subclass (relative to the Object), if we want to compare the Object values, we must implement our own equals method. let's take a look at the following program:
The following is a reference clip:
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
& Amp; endIndex = other. endIndex
& Field = other. field );
}
This is java in JDK. text. there seems to be nothing to say about the Standard Implementation of FieldPosition. I believe that most or most programmers believe that this is the correct and legal equals implementation. after all, it is the jdk api implementation. let's talk about it as a matter of fact:
The following is a reference clip:
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 the command to see what will be printed:
The following is a reference clip:
System. out. println (fp. equals (fp1); print true
System. out. println (fp1.equals (fp); print flase
Two objects have an asymmetric equals algorithm. Where is the problem? (brain teasers: Of course, the JDK implementation BUG )? I believe there are too many programmers (except those who do not know how to implement the equals method) who have used the instanceof operator to perform short-circuit optimization when implementing the equals method, I have used it for a long time.
Too many tutorials and documents are misleading. Some programmers who have a better understanding may know that such optimization may be wrong but cannot find the key to the problem. Another extreme is that hardcore experts who know this technical defect propose not to apply it like this. We know that "normally" to compare two objects, they "should" be of the same type. Therefore, short-circuit optimization is implemented using the instanceof operator. If the compared object is not of the same type as the current object, false is returned without comparison.
But in fact, "The subclass is an instance of the parent class", so if the subclass o instanceof parent class always returns true, then there will certainly be no short-circuit optimization, the following comparison may result in multiple situations: one is that an exception cannot be thrown when it is modeled as a parent class, and the other is that the private member of the parent class cannot be compared without the inheritance of the quilt class, in addition, the above asymmetry comparison is formed. There may be too many cases.
So, isn't it possible to use the instanceof operator for optimization? The answer is no. There are still many implementations in JDK that are correct. If a class is final, knowing that it cannot have sub-classes, why not use instanceof for optimization? In order to maintain SUN's development team's reputation, I do not describe which class, but a team member added the following comment when using this method for optimization:
The following is a reference clip:
If (this = obj) // quick check
Return true;
If (! (Obj instanceof XXXXClass) // (1) same object?
Return false;
There may be some questions, but I don't know how to do it (I don't know why I didn't call me...). So for non-final classes, how do I perform quick check?
The following is a reference clip:
If (obj. getClass ()! = XXXClass. class) return false;
Compared with the class Object of the compared object and the class of the current object, it seems that there is no problem. However, if the subclass of this class does not implement the equals method again, when the subclass is compared, obj. getClass () is certainly not equal to XXXCalss. class, that is, the equals of the subclass will be invalid, so
The following is a reference clip:
If (obj. getClass ()! = This. getClass () return false;
Is the correct comparison. Another quick check is if (this = obj) return true;
Do two objects compared by the equals method must be of the same type? I used "regular" above, which is also the wish of the vast majority of programmers, but in some special cases, we can compare different types, which does not violate the rules. However, this special case is very rare. an inappropriate example is that the equals of the Integer class can be compared with Sort to compare whether their values are of the same mathematical value. (In fact, this is not the case in JDK APIs, so I am saying it is not an appropriate example.) After completing quick check, we need to truly implement what you think is "equal ". There is no high requirement for implementing object equality. For example, if you implement the "person" class, you can think that they are equal as long as the names are the same, and other sex, can be ignored. This is not fully implemented, but if it is fully implemented, that is, all attributes must be the same, how to implement the equals method?
The following is a reference clip:
Class Human {
Private String name;
Private int ago;
Private String sex;
....................
Public boolean equals (Object obj ){
Quick check .......
Human other = (Human) ojb;
Return this. name. equals (other. name) & this. ago = ohter. ago & this. sex. equals (other. sex );
}
}
This is a complete implementation. However, sometimes the equals implementation is implemented in the parent class, and equals must work correctly after the quilt class inherits, at this time, you do not know what attributes the subclass actually extends, so the above method cannot fully implement equals.
A good method is to use reflection to fully implement equals:
The following is a reference clip:
Public boolean equals (Object obj ){
Quick check .......
Class c = this. getClass ();
Filed [] fds = c. getDeclaredFields ();
For (Filed f: fds ){
If (! F. get (this). equals (f. get (obj )))
Return false;
}
Return true;
}
For convenience of illustration, the above implementation omitted the exception. Such implementation is placed in the parent class, which ensures that the equals of your subclass can work correctly as you wish. The last point about the equals method is: If you overwrite the equals method yourself (it should be a crawler), you must overwrite the hashCode () at the same time (). this is a specification, otherwise .............
Let's take a look at this example:
The following is a reference clip:
Public final class PhoneNumber {
Private final int areaCode;
Private final int exchange;
Private final int extension;
Public PhoneNumber (int areaCode, int exchange, int extension ){
RangeCheck (areaCode, 999, "area code ");
RangeCheck (exchange, 99999999, "exchange ");
RangeCheck (extension, 9999, "extension ");
This. areaCode = areaCode;
This. exchange = exchange;
This. extension = extension;
}
Private static void rangeCheck (int arg, int max, String name ){
If (arg <0 | arg> max)
Throw new IllegalArgumentException (name + ":" + arg );
}
Public boolean equals (Object o ){
If (o = this)
Return true;
If (! (O instanceof PhoneNumber ))
Return false;
PhoneNumber pn = (PhoneNumber) o;
Return pn. extension = extension & pn. exchange = exchange & pn. areaCode = areaCode;
}
}
Note that this class is final, so there is no problem with this equals implementation. Let's test:
The following is a reference clip:
Public static void main (String [] args ){
Map hm = new HashMap ();
PhoneNumber pn = new PhoneNumber (123,389 42, 230 );
Hm. put (pn, "I love you ");
PhoneNumber pn1 = new PhoneNumber (123,389 42, 230 );
System. out. println (pn );
System. out. println ("pn. equals (pn1) is" + pn. equals (pn1 ));
System. out. println (hm. get (pn1 ));
System. out. println (hm. get (pn ));