gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:24:05 26 4
gpt4 key购买 nike

我想在名为 MyObject 的类中重写“public boolean equals(Object obj)”函数,用于名称和年龄

public class MyObject{
private String name;
private int age;
}

我怎么可以?

@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());

最佳答案

你的问题有点含糊,但如果唯一的目的是根据你想使用的属性使用不同的排序算法,那么最好使用 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()
}

您可以按如下方式使用:

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.

至于实际的 equals() 实现,我宁愿让它在两个 Person 对象在技术上或自然上相同时返回 true。您可以为此使用数据库生成的 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);
}
}

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

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;
}
}

在覆盖 equals() 时,不要忘记覆盖 hashCode()

另见:

关于java - 如何为一个类定义多个 equals() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3124179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com