下面是一个示例Java代码,定义了一个Student类,并重写了equals方法:

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Student)) {
            return false;
        }
        Student other = (Student) obj;
        return this.name.equals(other.name);
    }
}

在这个示例中,我们重写了equals方法,只要两个Student对象的name属性相同,就认为它们是相等的。如果两个对象的name不同,即使其他属性相同,也会被认为是不相等的。

要注意的是,重写equals方法时,还应该重写hashCode方法,以保证相等的对象具有相同的哈希码

java定义equals方法要求只要名字相同则认为内容一致。

原文地址: https://www.cveoy.top/t/topic/heWA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录