wood burning stoves 2.0*
The moose likes Java in General and the fly likes Understanding Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Understanding Comparator" Watch "Understanding Comparator" New topic
Author

Understanding Comparator

Amit J Thakur
Greenhorn

Joined: Sep 26, 2011
Posts: 13
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

Joined: Nov 23, 2011
Posts: 45
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

Joined: Aug 25, 2007
Posts: 8
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Understanding Comparator
 
Similar Threads
SCJP Objective 6.5 Question
array sorting
Sorting problem using CompareTo
Address Book Sort by Ascending & Descending order
need to find quicksort that sorts in descending order ..ARG