Java Reference
In-Depth Information
10
this
.day = day;
11 }
12
13 // Compares this calendar date to another date.
14 // Dates are compared by month and then by day.
15
public int
compareTo(CalendarDate other) {
16
if
(month != other.month) {
17
return
month - other.month;
18 }
else
{
19
return
day - other.day;
20 }
21 }
22
23
public int
getMonth() {
24
return
month;
25 }
26
27
public int
getDay() {
28
return
day;
29 }
30
31
public
String toString() {
32
return
month + "/" + day;
33 }
34 }
One of the major benefits of implementing the
Comparable
interface is that it
gives you access to built-in utilities like
Collections.sort
. As we mentioned
previously, you can use
Collections.sort
to sort an
ArrayList<String>
but not
to sort an
ArrayList<Point>
, because the
Point
class does not implement
Comparable
. The
CalendarDate
class implements the
Comparable
interface, so, as
the following short program demonstrates, we can use
Collections.sort
for an
ArrayList<CalendarDate>
:
1 // Short program that creates a list of the birthdays of the
2 // first 5 U.S. Presidents and that puts them into sorted order.
3
4
import
java.util.*;
5
6
public class
CalendarDateTest {
7
public static void
main(String[] args) {
8 ArrayList<CalendarDate> dates =
9
new
ArrayList<CalendarDate>();
10 dates.add(
new
CalendarDate(2, 22)); // Washington
11 dates.add(
new
CalendarDate(10, 30)); // Adams
Search WWH ::
Custom Search