Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# SCJP Objective 6.5 Question

karl czukoski
Greenhorn
Posts: 22
I found this question to be a bit challenging and was wondering if someone could walk through the question in detail to help me better understand.
result is 2 -2

dennis deems
Ranch Hand
Posts: 808
• 1

Shaikh Ali
Ranch Hand
Posts: 51
Let me know if the comments help.

karl czukoski
Greenhorn
Posts: 22
I am still having a difficult time understanding the descending order sort sequencing using the overridden compare, could i ask you to explain this in a little more detail?

dennis deems
Ranch Hand
Posts: 808
Remember the contract of the Comparator interface:

compare returns a zero if the first argument is equal to the second.
compare returns a negative integer if the first argument is less than the second
compare returns a positive integer if the first argument is greater than the second.

This language could be more explicit, but "a less than b" means that
a comes before b in the sort order. And "a greater than b" means that
a comes after b in the sort order.

Comparing numerical arguments is simple; we can do arithmetic on the arguments.
For an ascending sort we can return (first argument) - (second argument).

We could implement a comparator for Integers like this:

Suppose we are sorting Integers in ascending order, and we call compare(3, 7).
Our comparator subtracts 7 from 3 and returns the result -4.
This negative value tells the sort routine calling compare that argument a comes before argument b.
The sort routine doesn't care about the actual value -- just whether it is negative, zero, or positive.
If we call compare(6, 5), the comparator returns the value 1, telling us that 6 comes after 5.

If we want to reverse the sort order, to perform a descending sort, all we need do is swap the arguments:

Now the same call compare(3, 7) will subtract 3 from 7 and return 4,
and signify that 3 comes after 7 in the sort order.
Likewise compare(6, 5) now returns -1, meaning that 6 comes before 5.
All the values returned from the new implementation
are the inverse of those returned by the original implementation.

Note that in either implementation, a call like compare(5, 5) will return zero.