【问题标题】:How to set a class of my creation to be a key in a TreeMap (Java)如何将我创建的类设置为 TreeMap (Java) 中的键
【发布时间】:2011-01-04 06:40:12
【问题描述】:

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

event.put(date1, event)

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

event.get(date2)

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

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

【问题讨论】:

    标签: java map treemap


    【解决方案1】:

    有两种方式:

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

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

    【讨论】:

      【解决方案2】:

      您只需要让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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多