I know this seems to be a trivial question (and I have no doubt all the 'smart guys' would come and mark it as duplicate), but I havn't found any sufficient explanation to my question. Is it just me getting so much trouble to understand this simple subject?
I understand the basics behind Comparable
interface and how it works, but I have a truly difficulty to undestand HOW to determine the ORDER of the sort.
For example - I have this very simple Fruit
class:
public class Fruit implements Comparable<Fruit> {
private String fruitName;
private String fruitDesc;
private int quantity;
public Fruit(String fruitName, String fruitDesc, int quantity) {
this.fruitName = fruitName;
this.fruitDesc = fruitDesc;
this.quantity = quantity;
}
public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public String getFruitDesc() {
return fruitDesc;
}
public void setFruitDesc(String fruitDesc) {
this.fruitDesc = fruitDesc;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int compareTo(Fruit compareFruit) {
//ascending order
return this.quantity - ((Fruit) compareFruit).getQuantity();
}
Why when declaring the compareTo
like above it will sort by ascending order and when declaring it the opposite:
return ((Fruit) compareFruit).getQuantity() - this.quantity;
it will be by descending order?