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?
>Solution :
put takes an Integer as the key, so the 0 gets boxed to an Integer.
But containsKey takes an Object (see also), so the byte gets boxed to a Byte. This Byte does not equals the Integer that was put into the map since they are completely different classes, so containsKey returns false.