gpt4 book ai didi

java - TreeSet 不行,下面的代码有什么问题吗?

转载 作者:搜寻专家 更新时间:2023-11-01 01:21:24 26 4
gpt4 key购买 nike

下面的代码应该打印 3 个人,但实际上打印了 4 个人,为什么?Person("a", 1) 和 Person("a", 4) 应该被视为相同,但它们不是。


import java.util.TreeSet;
public class Person implements Comparable<Person>{
public Person(String name, int age){
this.name = name;
this.age = age;
}
public String name;
public int age;

@Override
public int compareTo(Person o) {
if(this.name.equals(o.name)){
return 0;
}else if(this.age <= o.age){
return -1;
}else {
return 1;
}
}
@Override public boolean equals(Object other) {
return name.equals(((Person)other).name);
}

@Override public int hashCode() {
return age * 31;
}
public static void main(String[] args) {
TreeSet<Person> persons = new TreeSet<Person>();
persons.add(new Person("a", 1));
persons.add(new Person("b", 3));
persons.add(new Person("c", 2));
persons.add(new Person("a", 4));//This should be ignored.

/*Here should print the first 3 persons, but it prints 4 persons*/
for(Person h: persons){
System.out.println(h.name + ":" +h.age);
}
}
}

结果:
一个:1
c:2
b:3
一:4

最佳答案

问题出在compareTo方法上,该方法根据年龄进行比较,却根据人名判断是否相等,与自身不一致。

插入前 3 个 Persons 后,树看起来像这样(原谅可怜的 ASCII 艺术):

    (c,2)
|
/\
(a,1) (b,3)

然后插入 (a,4),根据年龄将其与 (c,2) 进行比较。年龄 (4) 大于 (2),所以我们向右走。下一个比较是与 (b,3)。 (a,4) 再次变大,因此它作为新节点添加到树中(因为没有其他可比较的节点)。如果不是添加 (a,4),而是添加 (a,0),那么将与 (a,1) 进行比较,结果将是:

a:1
c:2
b:3

关于java - TreeSet 不行,下面的代码有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25449284/

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