IDEA自动重写的equals方法分析


一、创建类和自动重写equals方法

随便创建一个类,然后ctrl+insert生成equals方法

class Student {

    String name;
    String id;
    int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                name.equals(student.name) &&
                id.equals(student.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, id, age);
    }
}

IDEA自动重写的equals方法

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                name.equals(student.name) &&
                id.equals(student.id);
    }

二、分析

if (this == o) return true;

首先对对象的地址进行比较,既然地址一样,两个引用指向同一个对象那就没有比较的意义了,肯定返回true

if (o == null || getClass() != o.getClass()) return false;

对空引用进行判断,如果参数为空也没有比较的意义,直接返回false;其次比较两个类的类型,使用getClass方法进行获取,如果两个类的类型不一致也直接返回false

Student student = (Student) o;
        return age == student.age &&
                name.equals(student.name) &&
                id.equals(student.id);

从本质上来讲这块的目的就是当两个传入的对象是同一个类时,要根据他们的成员变量进行比较,如果成员变量的值都一样则认为两个对象相等
但下面这句的意义是什么?

Student student = (Student) o;

因为接受的参数是一个Object类对象,但实际传入的对象是一个Student类的对象,那么对于引用 Object o 而言,其实是Object o = (Student)对象
所以当需要比较子类对象的成员时需要进行转型操作

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值