0

I'm wondering why the following code snippet compiles in Java 7 without a warning

Map<String, Object> map = new HashMap<>();
map.put("key", 0);
if (map.get("key") != 0) {
    System.out.println("what?!");
}

Studying the generated bytecode reveals that the compiler boxes the 0 used in the if statement to an instance of Integer (using Integer.valueOf(0)) and then compares it with the result of the get using reference equality. Surprisingly enough the code doesn't print anything because instances of small integers are reused. But if one replaces 0 with say, 4096 in both cases, the program prints "what?!"

But my question is not why this code works or doesn't - it's an offense to write such a code. I'd rather expect the compiler to reject it completely! Why doesn't it?

  • 2
    It looks like you understood what happens. So your question is a little surprising. The compiler doesn't reject the code because of what you explained before. – Denys Séguret Dec 07 '15 at 08:08
  • 3
    You asked an answer, somehow. – Maroun Dec 07 '15 at 08:08
  • To be able to compare `Integers` using `==` can be convenient, so it's allowed. For legacy reasons, `map.get` returns an `Object` (and not a `V`). – aioobe Dec 07 '15 at 08:10

0 Answers0