A
aaronfude
Hi,
I have always assumed that HashMap.get(obj) looks for the key that
key.compareTo(obj) == 0. But apparently, that is not the case:
public static class GoodAsKeys implements Comparable {
private int myInt;
public GoodAsKeys(int inInt) { myInt = inInt; }
public int compareTo(Object inObject) {
return myInt - ((GoodAsKeys) inObject).myInt;
}
}
public static void main(String[] args) {
GoodAsKeys a = new GoodAsKeys(5);
GoodAsKeys b = new GoodAsKeys(5);
HashMap map = new HashMap();
map.put(a, "World");
System.out.println(map.get(b));
}
This program prints out "null". What have I missed here?
Many thanks in advance!
Aaron
I have always assumed that HashMap.get(obj) looks for the key that
key.compareTo(obj) == 0. But apparently, that is not the case:
public static class GoodAsKeys implements Comparable {
private int myInt;
public GoodAsKeys(int inInt) { myInt = inInt; }
public int compareTo(Object inObject) {
return myInt - ((GoodAsKeys) inObject).myInt;
}
}
public static void main(String[] args) {
GoodAsKeys a = new GoodAsKeys(5);
GoodAsKeys b = new GoodAsKeys(5);
HashMap map = new HashMap();
map.put(a, "World");
System.out.println(map.get(b));
}
This program prints out "null". What have I missed here?
Many thanks in advance!
Aaron