2Dee 2Dee - 2 months ago 12
Java Question

comparing Dates in java when used as keys in HashMap

I was trying to use a HashMap with

java.util.Date
as keys, but I came across this odd issue. When doing the below, I'm printing false.

Date testDate = new Date(timeInLongFormat);

HashMap<Date,Integer> datesAndInts;
datesAndInts.put(testDate, 0);

Iterator iterator = datesAndInts.keySet().iterator();

while (iterator.hasNext()) {
String key = iterator.next().toString();
System.out.println("comparing " + testDate + "with " + key + " result is " + testDate.equals(key));
// this call to equals() returns false.
Integer testInt = datesList.get(key); // testInt is null, since the Date key cannot be found ...
}


I would have expected the Date inserted as key and the Date returned by keySet to be identical, but they are not. Is that a normal behaviour ? Why ? Should I implement my own subclass of Date only comparing the time or something ?

Answer

You're comparing a Date object with a String one.

Iterator<Date> iterator = datesAndInts.keySet().iterator();  
while (iterator.hasNext()) {  
    Date key = iterator.next();
    System.out.println("comparing " + testDate + "with " + key + " result is " + testDate.equals(key)); 
    // this call to equals() returns true now.
}