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开发者_JAVA百科. 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?
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.
comparator.compare(a, b) < 0
<==> a < b
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
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.
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.
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;
}
精彩评论