Check out Manning's Countdown to 2014. Use discount code crdotd14 all month for 50% off every deal.
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# compareTo() and Collections.sort() Solution For Multiple Column Ordering (Ascending) question

James Dekker
Ranch Hand

Joined: Dec 09, 2006
Posts: 215
Am somewhat confused with the compareTo() and Collections.sort() behavior.

I am supposed to sort a column in ascending order using compareTo() & Collections.sort().

My criteria is (if the same number occurs than please sort the next available column).

(1) Document Number
(2) Posting Date
(3) Transaction Date
(4) Transaction Reference Number Comparison

Here's the code (which is executed in a calling method) that implements the Collection.sort() method:

Question(s):

(1) Am I doing the right thing? When a comparison = 0, it returns as -2. Is this correct behavior because I always thought it to be between -1,0,1.

(2) Should I be using the comparator?

Happy programming...
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 17076

4

James Dekker wrote:(1) Am I doing the right thing? When a comparison = 0, it returns as -2. Is this correct behavior because I always thought it to be between -1,0,1.

(2) Should I be using the comparator?

You could check the API documentation for the compareTo() method, if you wanted an answer to question (1). It says

Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

And since -2 is indeed a negative integer, that suggests you aren't doing the wrong thing by returning it.

As for (2): you said you were supposed to use compareTo(). So yes, you're supposed to use a Comparator.
James Dekker
Ranch Hand

Joined: Dec 09, 2006
Posts: 215
Paul,

Thanks so much for the response!

What I am asking is that if I don't use the comparator() that Collections.sort() is still invoking / calling the compareTo() method in my class, right?

Why is it returning -2?

Peace...
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19413

13

James Dekker wrote:(1) Am I doing the right thing? When a comparison = 0, it returns as -2. Is this correct behavior because I always thought it to be between -1,0,1.

THe return value is never guaranteed to be -1, 0 or 1. All you know is there are three outcomes: smaller than 0, 0 or larger than 0. -1 and 1 are just two specific cases, but -2 will be treated in exactly the same way as -1.

(2) Should I be using the comparator?

You should use compareTo which belongs to Comparable. Comparator's method is called compare. So in this case your class should implement CreditCardTransactionDetail, and Comparator is not needed. (I think Paul mixed up Comparable and Comparator.)
You should only use Comparator if:
1) your class doesn't implement Comparable.
2) you want a different sort order.

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6