The job of the compareTo method in the Comparable interface is to indicate which of two objectsthe message receiver and the message parametershould appear first. The code you will supply in compareTo should result in what is known as the natural, or default, sort order for CourseSessions. In other words, how do you normally want to sort a collection of CourseSession objects? The compareTo method must return an int value. If this return value is 0, then the two objects are equal for purposes of sorting. If the return value is negative, then the receiver (the object to which code sends the compareTo message) should come before the parameter in the sort order. If the value is positive, then the parameter should come before the receiver in the sort order. The String class implements the compareTo method in order to sort strings in alphabetical order. The following language test demonstrates the values returned from the compareTo method in the three possible scenarios. public void testStringCompareTo() { assertTrue("A".compareTo("B") < 0); assertEquals(0, "A".compareTo("A")); assertTrue("B".compareTo("A") > 0); } You will need to modify the CourseSession class to implement the Comparable interface and supply a definition for compareTo. An appropriate test to add to CourseSessionTest: public void testComparable() { final Date date = new Date(); CourseSession sessionA = CourseSession.create("CMSC", "101", date); CourseSession sessionB = CourseSession.create("ENGL", "101", date); assertTrue(sessionA.compareTo(sessionB) < 0); assertTrue(sessionB.compareTo(sessionA) > 0); CourseSession sessionC = CourseSession.create("CMSC", "101", date); assertEquals(0, sessionA.compareTo(sessionC)); } CourseSession must then declare that it implements the Comparable interface. It must also specify a bind type of CourseSessionyou want to be able to compare CourseSession objects to CourseSession objects. public class CourseSession implements Comparable<CourseSession> { ...
Since you bound the implementation of Comparable to the CourseSession, you must define the compareTo method so that it takes a CourseSession as parameter: public int compareTo(CourseSession that) { return this.getDepartment().compareTo(that.getDepartment()); } For the compareTo method implementation, you are returning the result of comparing the current CourseSession's department (this.getDepartment()) to the parameter CourseSession object's department (that.getDepartment()). At this point, both testComparable in CourseSessionTest and testReport in CouseReportTest should pass. |