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

发布于 2024-08-18 07:40:26 字数 412 浏览 3 评论 0原文

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

event.put(date1, event)

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

event.get(date2)

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北渚 2024-08-25 07:40:26

您只需要让 DateTime 实现 Comparable,类似于:

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 接口 已记录 此处

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.

情绪失控 2024-08-25 07:40:26

有两种方法:

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

  2. 定义一个实现 比较器 <日期时间>。根据需要定义其compare()方法。将该类的实例传递到 TreeMap 的构造函数中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文