java - 如何将我创建的类设置为 TreeMap 中的键 (Java)

标签 java dictionary treemap

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

event.put(date1, event)

将“事件”添加到集合中,以便我可以通过以下方式检索它

event.get(date2)

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

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

最佳答案

您只需要拥有 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 interface已记录here .

关于java - 如何将我创建的类设置为 TreeMap 中的键 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2050746/

相关文章:

java - 需要有关 Instanceof 运算符中类型转换的信息

python - 在 Python 中解包字典时,单(非双)星号 * 是什么意思?

Java 列表排序 : Is there a way to keep a list permantly sorted automatically like TreeMap?

java - TreeMap 内的 BufferedReader

java - 一直在寻找文本文件中 25 个最常见的单词

java - 递归java的堆栈溢出错误

java - jsp中无法连接mysql数据库

Java 文件光标

c++ - 对 std::map 进行排序

database - 如何访问 mule 中的有效负载值?