Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 513
aLittleMind Avatar asked Mar 17 '17 17:03

aLittleMind


People also ask

Do you need to override compareTo in Java?

So essentially you need to override compareTo() because you need to sort elements in ArrayList or any other Collection.

How do you override compareTo for string?

Comparator Interface: Implement the comparator interface in the class and override compare() method or pass the new comparator as the second argument in the sorting methods and change the sorting order according to the requirements.

Why compareTo () should be consistent to equals () method in Java?

This is because the comparison method of BigDecimal considers only the numeric value, but equals also considers the precision. Since 0.0 and 0.00 have different precisions, they are unequal even though they have the same numeric value.

What does compareTo () do in Java?

The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.


1 Answers

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);
}
like image 187
Roma Khomyshyn Avatar answered Oct 18 '22 23:10

Roma Khomyshyn