I have an ArrayList of object called Course and I'm trying to sort it in 2 ways, by courseID and course start time.
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;
}
}
Then I have these comparators:
//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()));
}
}
I sort them in my main method like this:
Collections.sort(courseList, new IDSorter());
Collections.sort(student.getStudentSchedule(), new StartTimeSorter());
The code works, I can get the list sorted by ID or startTime.... but I don't understand why. In the Course class the compareTo method is only comparing getCourseID.
How is the StartTimeSorter, which needs to compare courseBeginTime working then?
How can I rewrite to make more sense?