Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

530
Vistas
How to override compareTo (Java)

I'm a beginner in programming and I have two classes. First class is:

public class User implements Comparable<User>

with field int age, constructor and overrided method of interface Comparable:

 @Override
    public int compareTo(User user) {
        return user.age >= age ? -1 : 0;
    }

Second class is public class SortUser with a method to make a Set collection from a List:

public Set<User> sort(List<User> list) {
        Set<User> result = new TreeSet<>();
        for (User user : list) {
            result.add(user);
        }
        return result;
    }

It seems to me that all User objects in a Set should be sorted, but when I made a List with 3 User objects...

 User a = new User(1);
 User b = new User(2);
 User c = new User(3);
 List<User> list = new ArrayList<>();
 list.add(c);
 list.add(a);
 list.add(b);

(Now the list's order is: 312) ...and created a Set (TreeSet) from that list:

SortUser sortUser = new SortUser();
Set<User> set = sortUser.sort(list);

At the end I have a set with that order: 13, it means that only two objects are in the set. What is going wrong?

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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);
}
about 4 years ago · Santiago Trujillo Denunciar

0

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.

about 4 years ago · Santiago Trujillo Denunciar

0

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());
    }
};
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda