Java Reference
In-Depth Information
We have to replace the <T> in Comparable<T> . Whenever you implement
Comparable , you compare pairs of values from the same class. So a class called
CalendarDate should implement Comparable<CalendarDate> . If you look at the
header for the Integer class, you will find that it implements Comparable<Integer> .
Likewise, the String class implements Comparable<String> . So we need to change
the header to the following one:
public class CalendarDate implements Comparable<CalendarDate> {
...
}
Of course, claiming to implement the interface is not enough. We also have to
include appropriate methods. In this case, the Comparable interface includes just a
single method:
public interface Comparable<T> {
public int compareTo(T other);
}
Because we are using CalendarDate in place of T , we need to write a compareTo
method that takes a parameter of type CalendarDate :
public int compareTo(CalendarDate other) {
...
}
Now we have to figure out how to compare two dates. Each CalendarDate object
will contain fields that store the month and day. With calendars, the month takes
precedence over the day. If we want to compare January 31 (1/31) with April 5 (4/5),
we don't care that 5 comes before 31; we care instead that January comes before
April. So, as a first attempt, consider the following method that compares only the
months:
// compares only the months
public int compareTo(CalendarDate other) {
if (month < other.month) {
return -1;
} else if (month == other.month) {
return 0;
} else { // month > other.month
return 1;
}
}
We need to consider more than just the month, but before we do that, we can
improve on what we have here. This code uses a nested if/else construct to return the
standard values of -1 , 0 , and 1 , but a simpler option is available. We can simply return
 
Search WWH ::




Custom Search