空间做网站,西安网页设计设计培训,唐山做网站多少钱,wordpress主题 心理医生JAVA-重写equalse规范、技巧 1、自反性 任何非空引用x#xff0c;x.equalse(x) 应该返回true2、对称性 任何引用x和y#xff0c;当x.equals(y)返回true#xff0c;y.equals(x)也应返回true3、传递性 任何引用x、y和z#xff0c;当x.equalse(y)和y.equalse(z)#xff0c;那… JAVA-重写equalse规范、技巧 1、自反性 任何非空引用xx.equalse(x) 应该返回true2、对称性 任何引用x和y当x.equals(y)返回truey.equals(x)也应返回true3、传递性 任何引用x、y和z当x.equalse(y)和y.equalse(z)那么x.equalse(z)也应返回true4、一致性 如果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);}
}