我创建了一个DateTime类(包装了GregorianCalendar).我还创建了一个类Event.我想创建一个事件集合,我可以从中检索事件的日期.例如:event是Event类型; date1和date2的类型是DateTime,也是date1.equals(date2); 'events'是我的活动收藏.
event.put(date1, event)
Run Code Online (Sandbox Code Playgroud)
将"事件"添加到集合中,以便我可以检索它
event.get(date2)
Run Code Online (Sandbox Code Playgroud)
我想使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
有两种方法:
使DateTime实现Comparable <DateTime>.定义compareTo()方法.
定义一个实现Comparator <DateTime> 的类(可能是匿名的).根据需要定义其compare()方法.将该类的实例传递给TreeMap的构造函数.
| 归档时间: |
|
| 查看次数: |
160 次 |
| 最近记录: |