it looks sample to override the euqals mathod.however numerous override way will lead to wrong.and bring about terrible consequence,as we know,it is easiest that do not override the equals method to avoid those poblem.under the circumstance.object's every class only equals itself,if satisfy one of the following condition.this is the desird result:
- each instance of the class is uniqueness.for example as thread.Object provide euqals method is the right action for those class
- be indifferent to class have provided "logtical equality" test function.
- super class have overrided equals.it is also appropriate for subclass that extends from supclass's equals action.such as map extends abstractMap.
- class is private or package is private.it can affirm that its equals method will never called.
So.when we should override the Object.equals()?if class has its specific "logtical euqals" concept.and class has not been override the equals method to implement expect action.
during override the equals method.we must follow the following rules.
- reflexive.for every non-null reference value x. x.euqals(x) must return true.
- symmetrice.for every non-null reference value x and y x.euqals(y) must retrun same result with y.equals(x)
- transitive.for every non-null reference value x、y、z.base on symmetrice.such as x.equals(y) and y.equals(z).therefore z.equals(x)
- consistent.for every non-null value x and y.so long as there value do not alter.it will return same return value with different time.
for any non-null reference value x. x.equals(null) must return false.
package EffectiveJava;
/**
* @author 韦海涛
* @version 1.0
* @date 3/31/2021 1:05 AM
*/
public class No5Equals {
static class Example{
private int a;
public Example(int i){
this.a = i;
}
@Override
public boolean equals(Object obj) {
if(obj == this){//满足自反性
return true;
}else if(!(obj instanceof Example)){
return false;
}
Example temp = (Example)obj;
if(temp.a==this.a){
return true;
}else{
return false;
}
}
}
public static void main(String[] args) {
Example example1 = new Example(1);
Object object=null;
Example example2 = null;
Example example3 = new Example(2);
Example example4 = new Example(1);
System.out.println(example1.equals(object));
System.out.println(example1.equals(example2));
System.out.println(example1.equals(example3));
System.out.println(example1.equals(example4));
}
}
integrate all of these requirements,we can draw serveral conclusions.
- using == operation symbol to check "parameter instanceof the class's reference".if true,then return true,although it will expensive operation.
- using instanceof operation symbol "parameter is the true type"
- base on the instanceof test and transform right type
- for every key significant areain this class.check whether the area match the area of parameter
- when you have comleted the equals method ,ask yourself that the equals method hava accord with above rule.