tags:

views:

59

answers:

2

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); 'events' 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.

+8  A: 

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.

notnoop
+4  A: 

There are two ways:

  1. Make DateTime implement Comparable < DateTime >. Define the compareTo() method.

  2. 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.

MAK