【发布时间】:2014-03-17 08:48:55
【问题描述】:
我有一个名为 Course 的对象的 ArrayList,我试图以 2 种方式对它进行排序,按 courseID 和课程开始时间。
class Course implements Comparable<Course> {
private int courseID;
private String courseBeginTime;
// implement the compareTo method defined in Comparable
@Override
public int compareTo(Course course) {
if (getCourseID() > course.getCourseID()){
return 1;
} else if(getCourseID() < course.getCourseID()){
return -1;
} else {
return 0;
}
}
然后我有这些比较器:
//implement the comparators
class IDSorter implements Comparator<Course> {
public int compare(Course course1, Course course2) {
return Integer.compare(course1.getCourseID(), course2.getCourseID());
}
}
class startTimeSorter implements Comparator<Course> {
public int compare(Course course1, Course course2) {
return Integer.compare(Integer.parseInt(course1.getCourseBeginTime()),
Integer.parseInt(course2.getCourseBeginTime()));
}
}
我在我的主要方法中对它们进行排序,如下所示:
Collections.sort(courseList, new IDSorter());
Collections.sort(student.getStudentSchedule(), new StartTimeSorter());
代码有效,我可以得到按 ID 或 startTime 排序的列表....但我不明白为什么。在 Course 类中 compareTo 方法只是比较 getCourseID。
需要比较 courseBeginTime 的 StartTimeSorter 是如何工作的?
如何重写才能更有意义?
【问题讨论】: