The result of this run is "3" and I understand this result is because by the time we reach line "sysprint 2", "3" will be the last entry in the ranks TreeSet. What is confounding me is the sorting of the elements in the TreeSet. I am told that the compareTo() method in the Rank class "tries to sort the elements in descending order". Well, what displays after the execution of the "sysprint 1" line of code is:
Quite possibly the answer to my question is staring me in the face and I just don't see it. Can anybody please explain to me why, given the configured compareTo() method in the Rank class, the order of the elements in the ranks treeset is not in true descending order? Why am I wrong when I am expecting the elements in the TreeSet to look like:
The compare to method returns -1 that the first is smaller than the second. So if you say rank1.compareTo(rank2), it says rank1 is smaller. But if you say rank2.compareTo(rank1), it says rank2 is smaller. This is not a valid sort and clearly not descending order.
This is why the order is tied to the order added. The actual values added don't matter.
will sort the tree in descending order.
This means second rank is larger than the current rank, compareTo returns a positive result. The sorting algorithm will swap these two ranks in decending order if the result is positive.
If second rank is smaller than the current rank, compareTo returns a negative result. The sorting algorithm won't swap them.
This will create a descending sorted order.