JAVA-重写equalse规范、技巧
1、自反性
任何非空引用x,x.equalse(x) 应该返回true
2、对称性
任何引用x和y,当x.equals(y)返回true,y.equals(x)也应返回true
3、传递性
任何引用x、y和z,当x.equalse(y)和y.equalse(z),那么x.equalse(z)也应返回true
4、一致性
如果x和y引用的对象没有发生任何变化,那么反复x.equals(y)都应返回一样的结果
5、任何非空引用 x.euqals(null) 都应返回 false
6、重写equalse时,也要重写hashCode方法
equalse和hashCode定义必须一致,当x.equalse(y) 为true,那么x.hashCode()必须等于y.hashCode();
例
import java.util.Objects;public class Parent {
}class SubObject extends Parent {private String name;@Overridepublic boolean equals(Object otherObject) {//检测this和otherObject是否是同一个对象if (this == otherObject) return true;//null一律返回 falseif (otherObject == null) return false;//是否是同一类型,择一if (getClass() != otherObject.getClass()) return false;//1、当需要判断具体类型时if (!(otherObject instanceof Parent)) return false;//2、本类及其子类均可//将otherObject转换相应对象SubObject other = (SubObject) otherObject;//比较域,根据业务需求Objects.equals(this.name, other.name);return true;}@Overridepublic int hashCode() {//如果equalse方法比较的是name,那么hashCode方法就要散列namereturn Objects.hash(name);}
}