aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes SCJP Objective 6.5 Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "SCJP Objective 6.5 Question" Watch "SCJP Objective 6.5 Question" New topic
Author

SCJP Objective 6.5 Question

karl czukoski
Greenhorn

Joined: Dec 30, 2010
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

Joined: Mar 12, 2011
Posts: 808
Shaikh Ali
Ranch Hand

Joined: Jan 26, 2011
Posts: 51
Let me know if the comments help.

karl czukoski
Greenhorn

Joined: Dec 30, 2010
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

Joined: Mar 12, 2011
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: SCJP Objective 6.5 Question