Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading