一、创建类和自动重写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)对象
所以当需要比较子类对象的成员时需要进行转型操作