Cobnsider the following code:
public static void main (String[] args) {
Map<Number, String> map = new HashMap<Number, String>();
map.put(1L, "test");
System.out.println(map.get(1));
}
Why HashMap.get returns null? O_o It must return value for any object which hashCode function returns 1, is not it?
UPDATED
The problem is Map interface receives Object, not parameterized type. So I expected that any object can be a key, but HashMap implementation check type with equals, it was surprising for me.
And autoboxing is not the problem. I know, that 1 became Integer, and 1L to Long. But they have same hashcode. So as I thought any implementation Map#get should return value for any Object with same hashcode.
You're putting a key of 1L (Long
) and getting a key of 1 (Integer
).
They're not the same thing, so be careful.
Either remove the L from the put, or add the L to the get. Or even better, don't write them out as primitives and rely on autoboxing.
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