[Java Core]Java类的equals方法的实现
Java对equals方法的要求:
1. 自反性:x.equals(x) == true
2. 对称性:x.equals(y) == y.equals(x)
3. 传递性:
x.equals(y) == true && y.equals(z) == true => x.equals(z) == true
4. 一致性:若x,y均没有发生变化,x.equals(y)的结果不论调用多少次,都不发生变化
5. 非空结果:x.equals(null) == false
依据这几点要求,书中给出了一个完善的比较类的方法:
import java.util.Objects;
public class Employee {
public String member;
public Object obj;
public Employee(final String Member, final Object Obj){
member = Member;
obj = Obj;
}
public boolean equals(Object otherObj){
//refer to same object, return true
if(this == otherObj) return true;
//otherObj is null, return false
if(otherObj == null) return false;
//belong to different class, return false
if(this.getClass() != otherObj.getClass()) return false;
//solve the problem of comparison between super obj and child obj
if(!(otherObj instanceof Employee)) return false;
Employee other = (Employee)otherObj;
//in case obj or other.obj is null
return Objects.equals(obj, other.obj)
&& member.equals(other.member);
}
}