admin管理员组文章数量:1336633
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
1 Answer
Reset to default 7Boxing
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.
本文标签: dictionaryjava hashmapenexpected behaviour for containsKeyStack Overflow
版权声明:本文标题:dictionary - java hashmap : enexpected behaviour for containsKey - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742398491a2467404.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论