前言:
当做记了个笔记,读《Java 核心技术》看到的东西
@Override
public boolean equals(Object otherObject) {
if(this == otherObject)return true;
if(otherObject == null) return false;
if(getClass() != otherObject.getClass()) return false;
// 如果所有的子类都有相同的相等性语义,则可以使用instanceof来检测 如下
// if(!(otherObject instanceof ClassName)) return false;
Student other = (Student) otherObject;
return gender == other.gender // 这个用于普通的检测挺够了
&& Objects.equals(majoy,other.majoy); // 使用 Objects.equals 可以检测 null 与 null 的情况
}
// 重写了 equals 就必须重写 hashCode!!!
// 给Objects.hash() 传递各个参数,就可以得到新的 Hash 值
@Override
public int hashCode() {
return Objects.hash(majoy,gender);
}