# The compare() method

geet kaur
Ranch Hand
Posts: 79
i have an array
viz..int[] a={1,5,3,7,6,8,9};
now i want to sort the priority of the elements in teh array so that they culd be stored in a priority quue

i don't get how the compare method is assigning the priorities!!

Rob Spoor
Sheriff
Posts: 20707
68
Comparing in Java (with Comparable or Comparator) works as follows:
- if the return value is negative, the first value is considered smaller than the second
- if the return value is positive, the first value is considered larger than the second
- if the return value is 0, the values are considered to be equal.

So let's apply this to your example. Let's take 5 and 6. Compare(5, 6) will return 1, so 5 will be larger than 6. As a result, 5 will be put closer to the end than 6.

Campbell Ritchie
Sheriff
Posts: 50666
83
There is another problem with your compare() method. It will work as long as the parameter values remain within a restricted range, but you need to consider what happens if the values -1234567890 and 1234567890 are compared. Try it and see!

Steve Luke
Bartender
Posts: 4181
22
You also really don't need to write your own comparator for ints. There is an )]Arrays.sort(int[]) method that takes care of it for you.

And if you have Integers, Integers are Comparable as well, so you could just Arrays.sort(Object[]) them.

Campbell Ritchie
Sheriff
Posts: 50666
83
Yes, but this is probably a class exercise where they have been told to implement a compare() method . . .

And congratulations on the "Rancher" handle.

raju raj
Greenhorn
Posts: 1
How to sort the date fields...

for eg,

02/22/2009", "09/22/2007", "08/22/2008

if we declare string,
String[] names = {"02/22/2009", "09/22/2007", "08/22/2008"};

Then it will return as,

[02/22/2009, 08/22/2008, 09/22/2007].

so how to sort the date.

Rob Spoor
Sheriff
Posts: 20707
68
Again, write your own Comparator that uses SimpleDateFormat and Date. You then compare the Date objects.

Steve Luke
Bartender
Posts: 4181
22
Originally posted by Campbell Ritchie:
Yes, but this is probably a class exercise where they have been told to implement a compare() method . . .

Woops, sorry, I didn't get that.

Originally posted by Campbell Ritchie:
And congratulations on the "Rancher" handle.

Thanks