How to override compareTo (Java)

I am starting to program, and I have two classes. First grade:

public class User implements Comparable<User>

with field int age, constructor and overridden interface method. Compare:

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

The second class public class SortUserusing the method for creating the Set collection from the 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 the objects Userin the set should be sorted, but when I created a list with 3 Userobjects ...

 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 order of the list:) 312... and created Set( TreeSet) from this list:

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

In the end, I have Setwith this order:, 13that means in Setonly two objects. What is going wrong?

+4
source share
4

, . ?

@Override
public int compareTo(User user) {
  return Integer.compare(age, user.age);
}
+6

, TreeSet, . , .

Collections.sort(list)

, , - compareTo a 1 , , , , TreeSet.

+1

,

.

    public static Comparator<Employee> NameComparator = new Comparator<Employee>() {
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getName().compareTo(e2.getName());
    }
};

Integer

public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {

    @Override
    public int compare(Employee e1, Employee e2) {
        return (int) (e1.getSalary() - e2.getSalary());
    }
};
+1

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

   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);

 Set<User> list1 = new TreeSet(list);
0

Source: https://habr.com/ru/post/1672591/


All Articles