posted 12 years ago
The compare(T o1, T o2) returns negative integer, zero, positive integer if the object is less than, equal to or greater than the object passed as an argument.
Also the Collections.sort() internally calls, Arrays.sort which has the following logic when the comparator is passed as an argument:
So if the value returned by Comparator.compare() method is positive it swaps the elements. By changing the runtime objects, you change the values returned by the compare() method.
Case 1:
40,10 : returns -1 : No swap
10, 50 : returns 1 : Swap
40, 50 : returns 1 : Swap
... and so on
This will get you integer values in descending order.
Case 2:
40,10 : returns 1 : Swap
40, 50 : returns -1 : No Swap
50, 600 : returns -1 : No Swap
... and so on
This will get you integer values in ascending order