The following code should print 3 persons, but it actually print 4 persons, why? Person("a", 1) and Person("a", 4) should be treated as the same, but they are not.
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);
}
}
}
Result:
a:1
c:2
b:3
a:4