How to override compareTo (Java)
What you're doing with the TreeSet
is unnecessary. I'm not sure they're guaranteed to have certain ordering when iterated.
Just replace your sort method with
Collections.sort(list)
And my guess as to why an element is being dropped is your compareTo
method never returns a 1
in any case, so elements are always considered to be less than or equal to other elements, which is probably screwing with the TreeSet
.
As I see you have wrong implementation of compare method. Could you update it to?
@Override
public int compareTo(User user) {
return Integer.compare(age, user.age);
}
Please follow below methodology
In case of string.
public static Comparator<Employee> NameComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
};
In case of Integer values
public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return (int) (e1.getSalary() - e2.getSalary());
}
};