2

我创建了一个 DateTime 类(包含 GregorianCalendar)。我还创建了一个类事件。我想创建一个事件集合,我可以从中按日期检索事件。例如:事件是事件类型;date1 和 date2 是 DateTime 类型,也是 date1.equals(date2); “事件”是我的事件集合。

event.put(date1, event)

将“事件”添加到集合中,以便我可以通过

event.get(date2)

我想使用 TreeMap 来实现这个事件集合,因为我可能想要打印所有按日期排序的事件。

那么如何将 DateTime 设置为 TreeMap 的键呢?我应该在 DateTime 中添加什么?还有什么要做的?谢谢。

4

2 回答 2

9

您只需要具有DateTime工具Comparable<DateTime>,类似于以下内容:

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;
  }
}

Comparable 接口此处记录。

于 2010-01-12T17:04:42.990 回答
5

有两种方法:

  1. 使 DateTime 实现Comparable < DateTime >。定义 compareTo() 方法。

  2. 定义一个实现Comparator < DateTime >的类(可能是匿名的) 。根据需要定义其 compare() 方法。将该类的实例传递到 TreeMap 的构造函数中。

于 2010-01-12T17:06:59.583 回答