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.