dictionary - java hashmap : enexpected behaviour for containsKey - Stack Overflow

Here is a code snippet :public static void main(String[] args) {final byte key = 0;Map<Integer, Int

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?

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?

Share Improve this question edited Nov 20, 2024 at 1:10 Basil Bourque 341k122 gold badges934 silver badges1.3k bronze badges asked Nov 19, 2024 at 21:11 DmitryDmitry 2,1683 gold badges23 silver badges34 bronze badges 1
  • This question is similar to: Will HashMap's containsKey method in java, check for an integer if I put a character in it?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – Joe Commented Nov 20, 2024 at 1:30
Add a comment  | 

1 Answer 1

Reset to default 7

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742398492a4436429.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信