How to set a class of my creation to be a key in a TreeMap (Java)
I created a class DateTime (which wraps GregorianCalendar). I also created a class Event. I would like to create a collection of events from which I can retrieve an event by its date. For instance: event is of type Event; date1 and date2 are of type DateTime and also date1.equals(date2); '开发者_如何学Goevents' is my event collection.
event.put(date1, event)
will add 'event' to the collection so that I can retrieve it by
event.get(date2)
I think of using a TreeMap to implement this event collection because I might want to print all the events sorted by date.
So how to set DateTime to be a key of a TreeMap? What should I add to DateTime? and what else to do? Thanks.
You just need to have the DateTime
implement Comparable<DateTime>
, something along the lines of:
class DateTime implements Comparable<DateTime> {
GregorianCalendar calendar;
...
public int compareTo(DateTime other) {
if (calendar.equals(other.calendar))
return 0;
else if (calendar.before(other.calendar))
return -1;
else
return 1;
}
}
The Comparable interface is documented here.
There are two ways:
Make DateTime implement Comparable < DateTime >. Define the compareTo() method.
Define a class (may be anonymous) that implements Comparator < DateTime >. Define its compare() method as required. Pass an instance of that class into the constructor of your TreeMap.
精彩评论