Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why integer key do not work in HashMap?

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.

like image 827
Cherry Avatar asked Mar 21 '23 23:03

Cherry


1 Answers

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.

like image 171
Kayaman Avatar answered Apr 02 '23 09:04

Kayaman