• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Understanding Comparator

 
Amit J Thakur
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am trying to understand Comparators, and have a question on the same. I wanted to sort an integer in the descending order and did some search. Figured out a way how to do it but still have some confusion.

Following is the code:

What is not clear to me is that just by changing the runtime object, in the above case from input1.compareTo(input2) to input2.compareTo(input1),the order is getting reversed.

The compareTo() invocation just returns an integer vaule which is passed back. The code that would be calling compare() of the Comparator would either get a positive integer, zero or a negative integer. But how does it know what order(ascending/descending) it has to sort in?

Thanks in advance,

Amit
 
Cole Terry
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amit J Thakur wrote:
What is not clear to me is that just by changing the runtime object, in the above case from input1.compareTo(input2) to input2.compareTo(input1),the order is getting reversed.

The compareTo() invocation just returns an integer vaule which is passed back. The code that would be calling compare() of the Comparator would either get a positive integer, zero or a negative integer. But how does it know what order(ascending/descending) it has to sort in?



See the documentation of the Comparable.compareTo() method in Java API doc.
 
Anirudh Jhinaa
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic