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 ?
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.
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With