Dmitry
Dmitry

Reputation: 2168

java hashmap : enexpected behaviour for containsKey

Here is a code snippet :

public static void main(String[] args) {
    final byte key = 0;
    Map<Integer, Integer> test = new HashMap<>();
    test.put(0, 10);
    System.out.println(test.containsKey(key));
}

and I get false printed on console. Only if I cast key to int I get true, like this

System.out.println(test.containsKey((int)key));

Can someone explain what is going on here?

Upvotes: 2

Views: 46

Answers (1)

Sweeper
Sweeper

Reputation: 274235

Boxing

put takes an Integer as the key. So the primitive numeric literal 0 in put(0, 10) gets boxed to an Integer object.

But containsKey takes an Object (see also). So the byte gets boxed to a Byte object. This Byte object does not equals the Integer object that was put into the map since they are completely different classes. Therefore containsKey returns false.

Primitive type Object type, after auto-boxing
int java.lang.Integer
byte java.lang.Byte

See Auto-boxing, at Wikipedia. And Autoboxing tech note at Oracle.com.

Upvotes: 7

Related Questions