我一直在查several tutorials他们似乎都有不同的算法来编写比较函数。以下是一些示例:
public int compareTo(Fruit compareFruit) {
int compareQuantity = ((Fruit) compareFruit).getQuantity();
//ascending order
return this.quantity - compareQuantity;
//descending order
//return compareQuantity - this.quantity;
}
@Override
public int compare(Employee e1, Employee e2) {
return (int) (e1.getSalary() - e2.getSalary());
}
有没有一个“向导”可以自动生成这个?
最佳答案
您可能想看看 Apache Commons Lang library ,其中包含一个 CompareToBuilder 类,可以使构建compareTo() 变得更容易一些。
http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.1/index.html
关于java - 如何编写比较器的比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22697014/