如何为类定义多个equals()函数

Zee*_*han 4 java

我想在我的名为MyObject的类中覆盖名称和年龄的"public boolean equals(Object obj)"函数,其结构如下所示

public class MyObject{
       private String name;
       private int age;
}
Run Code Online (Sandbox Code Playgroud)

我怎么能够 ?

@balusC:

那这个呢 ?

vo  = new MyObject() {
                    public boolean equals(Object obj) {
                        return ((MyObject)obj).name().equals(this.getName());

                    }


vo  = new MyObject() {
                    public boolean equals(Object obj) {
                        return ((MyObject)obj).age() == (this.getAge());
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 6

你的问题有点模糊,但如果唯一的目的是根据你想要使用的属性而有不同的排序算法,那么请使用a Comparator.

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

    public static Comparator COMPARE_BY_NAME = new Comparator<Person>() {
        public int compare(Person one, Person other) {
            return one.name.compareTo(other.name);
        }
    }

    public static Comparator COMPARE_BY_AGE = new Comparator<Person>() {
        public int compare(Person one, Person other) {
            return one.age > other.age ? 1
                 : one.age < other.age ? -1
                 : 0; // Maybe compare by name here? I.e. if same age, then order by name instead.
        }
    }

    // Add/generate getters/setters/equals()/hashCode()/toString()
}
Run Code Online (Sandbox Code Playgroud)

您可以使用如下:

List<Person> persons = createItSomehow();

Collections.sort(persons, Person.COMPARE_BY_NAME);
System.out.println(persons); // Ordered by name.

Collections.sort(persons, Person.COMPARE_BY_AGE);
System.out.println(persons); // Ordered by age.
Run Code Online (Sandbox Code Playgroud)

至于实际的equals()实现,当两个Person对象在技术上或自然相同时,我宁愿让它返回true .您可以使用DB生成的PK来比较技术标识:

public class Person {
    private Long id;

    public boolean equals(Object object) {
        return (object instanceof Person) && (id != null) 
             ? id.equals(((Person) object).id) 
             : (object == this);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者只是比较每个属性以比较自然身份:

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

    public boolean equals(Object object) {
        // Basic checks.
        if (object == this) return true;
        if (object == null || getClass() != object.getClass()) return false;

        // Property checks.
        Person other = (Person) object;
        if (name == null ? other.name != null : !name.equals(other.name)) return false;
        if (age != other.age) return false;

        // All passed.
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

覆盖hashCode()时不要忘记覆盖equals().

也可以看看: