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;
}