gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:49:45 25 4
gpt4 key购买 nike

将包含在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com