Getting values ​​from java.util.Map

I have one Map<Date, String. I have two Date objects a, bthat are equal. I put the string value on the card associated with the key a. Then I try to get the map value associated with the keys aand b, but only areturns the value that I put. Is it possible to get the value using the key b. I know this is possible when the keys are simple strings. Why does this not work with other types 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;
    }
}

}

Output:

sweet
null
+4
source share
4 answers

HashMap , hashCode(), , hashCode.

hashCode() overriden ( ):

@Override
public int hashCode(){
   return ymd;
}

:


+5

, hashCode. - , . , . , , - . HashMap hashCode b hashCode a hashCode, a b.

+2

hashCode() Date

Date

    @Override
    public int hashCode() {              
          return ymd;
    }

sweet
sweet
+1

String, Integer hasCode . equals() true, hasCode(), - a b. Map map (b) null.

0
source

All Articles