java - HashSet 包含自定义对象的问题

标签 java hashcode hashset

将包含在 HashSet 中的自定义类

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

我的 HashSet 测试失败了

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

我期待 personSet.contains(p1) 通过。为什么它返回错误? 谢谢 斯里

最佳答案

因为 p1.hashCode() 在您修改 p1 时发生了变化,因此无法再在哈希表中的原始索引处找到它。永远不要让哈希值依赖于可变字段。

(你很幸运,它在测试期间失败了;它也可能成功了,只是在生产中失败了。)

关于java - HashSet 包含自定义对象的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5110376/

相关文章:

java - tomcat编译jsp失败

java - ArrayList .contains() 不起作用

java - HashSet cannot be converted to String error with instanceof 运算符

java - 元素存在但 `Set.contains(element)` 返回 false

c# - 用于将漂亮的 HashSet 表示形式作为字符串的内置方法?

java - 响应用户输入的 Applet 绘图

java - 如何在RocketMQ中配置2个broker之间的消息 channel

java - 使 JavaFX 应用程序窗口外部元素在所有操作系统中保持相似

java - 自动检查equals、hashCode和compareTo一致性的技术?

java - "equals any of some fields are equal"的 hashCode 实现