I have a misunderstanding about Comparator interface and its method compare here is the following code and i am wondering why compare method return -33 i believe that it should return 33
import java.util.*;
public class Sorted implements Comparable<Sorted>, Comparator<Sorted> {
private int num;
private String text;
Sorted(int n, String t) {
this.num = n;
this.text = t;
}
public String toString() {
return "" + num;
}
public int compareTo(Sorted s) {
return text.compareTo(s.text);
}
public int compare(Sorted s1, Sorted s2) {
System.out.println(s1.num-s2.num); // return -33
return s1.num - s2.num;
}
public static void main(String[] args) {
Sorted s1 = new Sorted(88, "a");
Sorted s2 = new Sorted(55, "b");
TreeSet<Sorted> t1 = new TreeSet<>();
t1.add(s1); t1.add(s2);
TreeSet<Sorted> t2 = new TreeSet<>(s1);
t2.add(s1); t2.add(s2);
System.out.println(t1 + " " + t2);
System.out.println(s1.num-s2.num); // prints 33
} }
You probably know that if
a-b=cthenb-a=-c.What happens here is very similar. You seem to have assumed that
TreeSetis calls thecomparemethod like this:(Note that I used
s1ands2for demonstrative purposes. They are obviously not in scope inTreeSet.s1is the same instance as yours1ands2is the same instance as your s2`.)But it could call
comparelike this as well:couldn't it?
If it called it the second way, then the result of
-33is to be expected.EDIT:
I looked into the source code for
TreeSet.addand found that it callsTreeMap.putwith the item you are adding as the key. If you look further intoTreeMap.put, you will find:This shows that
TreeSetindeed callscomparethe way I described.EDIT:
As Holger said in the comments, you should not implement
Comparatorby subtracting the two integers. Instead, you should useInteger.compare:In fact, there is no need to implement
Comparatorat all, you can pass in aComparator.comparingInt(s -> s.num)when you create theTreeMap: