我知道这似乎是一个微不足道的问题(我毫不怀疑所有“聪明人”都会来并将其标记为重复),但我还没有找到对我的问题有任何充分的解释强>。难道只有我这么费劲去理解这个简单的主题吗?
我了解 Comparable
背后的基础知识界面及其工作原理,但我确实很难理解如何来确定排序的顺序。
例如 - 我有这个非常简单的 Fruit
类:
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();
}
为什么在声明 compareTo
时像上面一样,它将按升序排序,并且在声明它时相反:
return ((Fruit) compareFruit).getQuantity() - this.quantity;
按降序排列?
最佳答案
来自Javadoc
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
关于java - 实现 'Comparable' 时如何定义排序顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069814/