最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论