您需要覆盖从 Object 继承的 equals 和 hashcode 方法。 Java 不知道这两个对象是否相等,除非您告诉它要比较什么。 Hashset 类将调用对象的 equals 方法进行比较
让我们以汽车为例,它有两个字段;类型和颜色。如果两个对象的类型和颜色相同,则它们将被视为相等。
如果我们不重写 equals 方法,当我们有两个相同的对象时,我们会得到 false
public class Car {
private String type;
private String color;
public Car(String type, String color) {
super();
this.type = type;
this.color = color;
}
public static void main(String[] args) {
Car car1 = new Car("Suv","Green");
Car car2 = new Car("Suv","Green");
System.out.println(car1.equals(car2)); //false
}
}
在这个例子中,我们将告诉 java 我们希望它如何通过覆盖 equals 方法来比较对象
private String type;
private String color;
public Car(String type, String color) {
super();
this.type = type;
this.color = color;
}
@Override
public boolean equals(Object obj) {
if (this.getClass() == obj.getClass()){
Car other =(Car)obj;
if(this.color.equals(other.color) && this.type.equals(other.type)){
return true;
}
}
return false;
}
public static void main(String[] args) {
Car car1 = new Car("Suv","Green");
Car car2 = new Car("Suv","Green");
System.out.println(car1.equals(car2)); //true
}
运行这个例子你会得到真实的。
如果你测试一个没有覆盖等于的对象的哈希集,你将在它们中包含两个类,因为 java 认为它们是不同的对象,因为等于返回 false。用覆盖的方法测试它,你只会有一个
同样,任何时候你重写equals你也应该重写hashCode。使用您最喜欢的 IDE 来帮助您解决这些问题。
希望这会有所帮助!