Search code examples
javadatedictionarytreemap

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


I just observed when I create a TreeMap based on a Date as a key, and sorted by date, functions like remove(Date key) or containsKey(Date key) don't work even if the date is well present in the Map. Furthermore, the equals function of Date works well.

So, does anyone know why it doesn't work?

I'm using the old Java 6u43 and I create my Map like that:

    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

Solution

  • The problem is not Date but your broken comparator (for example, it returns -1 if two dates are equal). Why not use the default one?

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

    should work as expected.

    For reference, this is how the comparator is implemented in the Date class (in Java 8 - not sure if it's changed since Java 6):

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