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?
source
share