Why can't the compiler/JVM just make autoboxing "just work"?

Posted by Pyrolistical on Stack Overflow See other posts from Stack Overflow or by Pyrolistical
Published on 2010-04-08T19:00:52Z Indexed on 2010/04/08 20:13 UTC
Read the original article Hit count: 456

Filed under:
|
|
|

Autoboxing is rather scary. While I fully understand the difference between == and .equals I can't but help have the follow bug the hell out of me:

    final List<Integer> foo = Arrays.asList(1, 1000);
    final List<Integer> bar = Arrays.asList(1, 1000);
    System.out.println(foo.get(0) == bar.get(0));
    System.out.println(foo.get(1) == bar.get(1));

That prints

true
false

Why did they do it this way? It something to do with cached Integers, but if that is the case why don't they just cache all Integers used by the program? Or why doesn't the JVM always auto unbox to primitive?

Printing false false or true true would have been way better.

EDIT

I disagree about breakage of old code. By having foo.get(0) == bar.get(0) return true you already broke the code.

Can't this be solved at the compiler level by replacing Integer with int in byte code (as long as it is never assigned null)

© Stack Overflow or respective owner

Related posts about java

Related posts about autoboxing