I’m implementing a TreeSet which will sort by person’s age, but a person will not be saved in set if person’s name is equals. I implement equals and hashcode, but this set will save all persons even if they have the same name. I don’t know why.
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
if(this.getAge()<o.getAge()){
return -1;
}
return this.getAge() == o.getAge()?0:1;
}
@Override
public boolean equals(Object object){
return name.equals(((Person)object).getName());
}
@Override
public int hashCode(){
return name.hashCode();
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public static void main(String[] args){
Set<Person> set = new TreeSet<Person>();
set.add(new Person("Jack",30));
set.add(new Person("Jack",20));
System.out.println(set);
}
}
You can add
in the beginning of your
compareTo()function. That way TreeSet can assumea.equals(b)is equivalent toa.compareTo(b) == 0and you still get the ordering by age as all names in the set are different.