I have Map<Date, String. I have two Date objects a, b that are equal. I put a string value to the map associated with key a. Then I try to get map value associated with keys a and b but only a returns value that I've put. Is it possible to get my value with b key. I know this is possible when keys are simple strings. Why this doesn't work with other type of objects?
public class Main {
public static void main(String[] args) {
Map<Date, String> map = new HashMap<Date, String>();
Date a = new Date(20131105);
Date b = new Date(20131105);
map.put(a, "sweet");
System.out.println(map.get(a));
System.out.println(map.get(b));
}
static class Date {
private int ymd;
public Date(int ymd) {
this.ymd = ymd;
}
public int getYmd() {
return ymd;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Date) {
return ((Date) obj).ymd == ymd;
}
return false;
}
}
}
The output is:
sweet
null