为什么 Map 不能使用日期作为键?

Why Map doesn't work with a Date as a key?

我刚刚观察到,当我基于 Date 作为键创建一个 TreeMap,并按日期排序时,像 remove(Date key)containsKey(Date key) 这样的函数不会即使日期很好地显示在地图中也能正常工作。此外,Date 的 equals 功能也很好

所以,有人知道为什么它不起作用吗?

我正在使用旧的 Java 6u43 并且我这样创建我的地图:

    Map<Date, Integer> hourMap = new TreeMap<Date, Integer>(new Comparator<Date>() {
        @Override
        public int compare(Date d1, Date d2) {
            return d1.after(d2) ? 1 : -1;
        }
    });
    Date now = DateUtils.parseDate("04:00:00", "HH:mm:ss");
    hourMap.put(now, 12);
    hourMap.remove(now); // doesn't work
    boolean test = hourMap.containsKey(now); // return false

问题不在于日期,而是你损坏的比较器(例如,如果两个日期相等,它 returns -1)。为什么不用默认的?

Map<Date, Integer> hourMap = new TreeMap<Date, Integer>();

应该按预期工作。

供参考,这是比较器在日期 class 中的实现方式(在 Java 8 中 - 不确定自 Java 6 以来它是否发生了变化):

long thisTime = getMillisOf(this);
long anotherTime = getMillisOf(anotherDate);
return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));