omkar sirra omkar sirra - 1 year ago 65
Java Question

Implementation of compare() method in custom created Comparators

class IntegerComparator implements Comparator<Integer>
public int compare(Integer o1, Integer o2) {
if(o1 < o2)
return 1;
else if(o1 > o2)
return -1;
return 0;

It gives the descending order. I know it. I remember it blindly. I dont understand why the implementation has to be like this.

I expect the results to be ascending order. Because in ascending order, the o1 should be always less than o2 if you take any two adjacent elements. But It gives the descending order which I dont expect.

Can someone demystify the logic behind it


  • When the elements are swapped. Is it when the compare returns 1 ?

Answer Source

Remember that:

  • returning -1 put the first object before the second (generally value less than 0),
  • returning 0 do nothing,
  • returning 1 put the first object after the second (generally value more than 0).

This is repeated over all the object to compare and you have a ascending sorting. See bubble sorting algo on google/youtube.

You can see:


To get a new Comparator with a reverse order of yours.

enter image description here

In this animation:

  • a > b -> return +1 (a moving right, after b)
  • a < b -> return -1 (a moving left, before b)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download