java - 实现 'Comparable' 时如何定义排序顺序?

标签 java sorting comparable

我知道这似乎是一个微不足道的问题(我毫不怀疑所有“聪明人”都会来并将其标记为重复),但我还没有找到对我的问题有任何充分的解释。难道只有我这么费劲去理解这个简单的主题吗?

我了解 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/

相关文章:

arrays - 为什么选择排序可以稳定或不稳定

Java Comparator 使用 .reverseOrder() 但有一个内部类

java - 如何为 BitSet 类型的元素创建 SortedSet(例如 TreeSet)

java - WebView Malayalam Unicode 复杂/组合字母

java - 是否可以实现带有签名 List<Class< 的方法?在 Java 中扩展注释>>?

java - 带有 JavaFX 和 FXML 的 MVC

java - osgi NoClassDefFoundError - jar 目录

javascript - 找到一组数字的最大值(JS)

arrays - 力扣代码 : sort an array of n objects with k different colors

java - 定义一个实现可比较的接口(interface)