【发布时间】:2014-02-14 22:04:47
【问题描述】:
我已经阅读了一些关于如何根据对象的属性对对象进行排序的教程。例如,如果我们有一个名为 person 的类,它有一个名为 name 的属性,我们只需实现 Comparable 接口并覆盖 compareTo。
但是,不同的教程会显示您在 compareTo 中编写的不同代码,例如这里是 one way:
public int compareTo(Object o) throws ClassCastException {
Date d = (Date)o; // If this doesn't work, ClassCastException is thrown
int yd = year - d.year;
int md = month - d.month;
int dd = day - d.day;
if (yd != 0) return yd;
else if (md != 0) return md;
else return dd;
}
但这里是different way 来编写 compareTo 方法:
@Override
public int compareTo(Student1 o) {
return Integer.compare(grade, o.grade);
}
因此,我完全不知道编写正确的 compareTo 需要什么算法或公式
【问题讨论】: