是的,您必须在 MyClass 类中覆盖您的equals()方法。
这是一个例子:
public class MyClass {
private String name;
private String gender;
public MyClass(String name, String gender) {
this.name = name;
this.gender = gender;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
MyClass other = (MyClass) obj;
if (gender == null) {
if (other.gender != null) return false;
} else if (!gender.equals(other.gender)) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
请注意,当您重写equals () 方法时,重写hashcode ()是一种很好的编程习惯,特别是在哈希概念出现的场景中。例如HashMap 。
然后,您可以进行如下比较:
public class Test {
public static void main(String args[]) throws Exception {
MyClass myFirstClass = new MyClass("John", "Male");
MyClass mySecondClass = new MyClass("Jessica", "Female");
Set<MyClass> mySet = new HashSet<MyClass> ();
mySet.add(myFirstClass);
mySet.add(mySecondClass);
MyClass myDupeClass = new MyClass("Jessica", "Female");
for (MyClass someClass: mySet) {
if (someClass.equals(myDupeClass)) {
System.out.println("Match found for: " + someClass.getName());
}
}
}
}
输出符合预期
Match found for: Jessica