对集合使用我自己的 equals 方法

using my own equals method for a set

所以我正在尝试重写 equals() 所以当我制作一组我的对象时它会正常运行。

这是我正在使用的代码(暂时忽略类型安全)

@Override
public boolean equals(Object o) {
    MyClass myObject1 = (MyClass) o;
    MyClass myObject2 = (MyClass) this;
    if (myObject1.property == myObject2.property)
        return true;
    return false;
}

你可以假设只有一个 属性 并且它是一个像 int 这样的原始类型。

但是,如果我将两个相同的对象添加到一个集合中,它们都会被添加。

这是因为你违反了Java requirement for overriding equals:

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

如果没有实施 hashCode returns 相等对象的相同值,哈希集通常会将具有不同哈希码的对象视为不同的对象,除非存在哈希冲突。

一旦您为 class 实施 hashCode,问题就会解决。

您的 类 必须覆盖 equalshashCode

来自集合Documentation

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

The Set interface places additional stipulations, beyond those inherited from the Collection interface, on the contracts of all constructors and on the contracts of the add, equals and hashCode methods.

要覆盖这些方法,您可以这样做:

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

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
            // if deriving: appendSuper(super.hashCode()).
            append(name).
            append(age).
            toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Person))
            return false;
        if (obj == this)
            return true;

        Person rhs = (Person) obj;
        return new EqualsBuilder().
            // if deriving: appendSuper(super.equals(obj)).
            append(name, rhs.name).
            append(age, rhs.age).
            isEquals();
    }
}

如果你像下面这样实现 hashCode() 方法,它会工作得很好。

public int hashCode(){
    return this.property.hashCode();
  }

请注意,当您覆盖对象 class 的 equals 方法时,必须覆盖对象 class 的 hashcode 方法。

在给定 Set 的 add 方法调用期间,首先调用 hashCode 方法 - 一旦它们(如电话目录索引)相同,就会检查 equals 方法。