Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing Dates in java when used as keys in HashMap

Tags:

java

date

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 ?

like image 442
2Dee Avatar asked Dec 15 '22 03:12

2Dee


2 Answers

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.
}
like image 141
Alexis C. Avatar answered Dec 17 '22 16:12

Alexis C.


You're not comparing the date with the key in the HashMap (which would be the exact same Date object). You're comparing a Date with a String, which happens to be the result of calling toString() on the date. A Date and a String will never be equal.

like image 40
JB Nizet Avatar answered Dec 17 '22 16:12

JB Nizet