哈希集包含自定义对象的问题

2022-09-03 04:17:27

我的自定义类,它将包含在哈希集

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "hashcode='" + this.hashCode() + '\'' +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

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

        Person person = (Person) o;

        if (age != person.age) return false;
        if (!name.equals(person.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + age;
        return result;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

我的哈希集测试失败

   public void hashSetTest() {
        Set<Person>  personSet = new HashSet<Person>();
        Person p1 = new Person("raghu", 12);
        Person p2 = new Person("rimmu", 21);

        personSet.add(p1);
        personSet.add(p2);


       p1.setName("raghus");
       p1.setAge(13);

       int i2 =p1.hashCode();
       System.out.println(personSet.size() + ": "+ p1.hashCode()+" : "+personSet.contains(p1)+ " : "+i2);
    }

Iam 期望 personSet.contains(p1) 通过。为什么它返回 false?谢谢斯里


答案 1

因为修改时会发生变化,所以在哈希表中的原始索引处找不到它了。切勿让哈希值依赖于可变字段。p1.hashCode()p1

(你很幸运,它在测试过程中失败了;它可能同样成功了,只是在生产中失败了。


答案 2

HashSet 实现 Set。ApiDoc 指定:

Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set.

在您的示例中,情况就是如此,因为更改 或 on 会影响相等比较。因此,根据 ApiDoc,在您的案例中,Set 的行为是未指定的。nameagep1