15

Every time I need to implement a comparator, I get stuck trying to remember when I should return -1 and when 1, and I have to look it up.

I mean, obviously -1 is less, so it implies that first is less than second. But whenever I say that to myself, I get that nagging "are you sure?" feeling. I suspect part of my confusion comes from implementing it the other way around whenever I need a descending sort.

What do you use to remember which is which?

itsadok
  • 28,822
  • 30
  • 126
  • 171

5 Answers5

11

I use this simple "substraction" mnemonic:

first - second

So, if first is "less" than second you'll get negative result, otherwise - positive or zero if they are equal.

xappymah
  • 1,624
  • 10
  • 14
6

comparator.compare(a, b) < 0 <==> a < b

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
Tadeusz Kopec for Ukraine
  • 12,283
  • 6
  • 56
  • 83
5

I am not sure what you mean by mnemonic. However, I have had a very similar cognitive dissonance.

I am very visual, so I use the number line (the one I was taught in grade school). I just visualize the negative numbers as "left", 0 as "center" and positive numbers as "right". That the corresponds to the truth: -1 < 0 < 1

chaotic3quilibrium
  • 5,661
  • 8
  • 53
  • 86
2

I remember the base integer case (pseudocode):

int comparator(int a, int b) {
   return a-b;
}

So if we give in a small a and a large b which is the first < last we get a negative result.

I have a more visual memory, so remembering the "structure" of that function is easy and natural for me.

davin
  • 44,863
  • 9
  • 78
  • 78
0

I used to always check the documentation when implementing Comparator and Comparable interfaces.

Question: Compare a and b
Lets first at look ascending order since the descending order will be just the inverse of whatever we do.
Question can be translated to given two numbers a and b, how would you put them on the number line?
if a < b, then we will put a on the negative side and b on the positive side.
else if a = b then we will put both at the center (at 0)
otherwise b will be on the negative side and a will be on the positive side.

enter image description here

Comparator Implementation:
Here you are comparing a to b.

 @Override
    public int compare(MyClass a, MyClass b) { //always good to rename your variables like this to be consistent 
        return a.f1 - b.f1; 
    }

Comparable Implementation:
Here you are comparing this to other.

@Override
    public int compareTo(MyClass other) { // this is same as compare(this, other)
        return this.f1 - o.f1;
    }
dsharew
  • 10,377
  • 6
  • 49
  • 75