Java Reference
In-Depth Information
the difference between
month
and
other.month
, because it will be negative when
month
is less than
other.month
, it will be
0
when they are equal, and it will be positive
when
month
is greater than
other.month
. So, we can simplify the code as follows:
// still uses only the month, but more compact
public int compareTo(CalendarDate other) {
return month - other.month;
}
It is a good idea to keep things simple when you can, so this version is preferable
to the original one. It returns slightly different values than the earlier version, but it
satisfies the contract of the
Comparable
interface just as well. However, the code still
has a problem.
Consider, for example, a comparison of April 1 (4/1) and April 5 (4/5). The current
version of
compareTo
would subtract the months and return a value of
0
, indicating that
these two dates are equal. However, the dates aren't equal: April 1 comes before April 5.
The day of the month becomes important only when the months are equal. If the
months differ, we can use the months to determine order. Otherwise (when the
months are equal), we must use the day of the month to determine order. This com-
mon ordering principle is present in many tasks. We can implement it as follows:
public int compareTo(CalendarDate other) {
if (month != other.month) {
return month - other.month;
} else {
return day - other.day;
}
}
It is still possible for this code to return
0
. Suppose that we have two
CalendarDate
objects that both store the date April 5 (4/5). The months are equal,
so the program returns the difference between the days. That difference is 0, so the
program returns
0
, which correctly indicates that the two dates are equal.
Here is a complete
CalendarDate
class with the
compareTo
method, two acces-
sor methods, and a
toString
method:
1 // The CalendarDate class stores information about a single
2 // calendar date (month and day but no year).
3
4
public class
CalendarDate
implements
Comparable<CalendarDate> {
5
private int
month;
6
private int
day;
7
8
public
CalendarDate(
int
month,
int
day) {
9
this
.month = month;
Search WWH ::
Custom Search