高质量的重写equals方法

        前言:

当做记了个笔记,读《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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值