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

前端 未结 6 1289
广开言路
广开言路 2020-12-31 07:40

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 m

6条回答
  •  囚心锁ツ
    2020-12-31 08:28

    Integers in the byte range are the same object, because they are cached. Integers outside the byte range are not. If all integers were to be cached, imagine the memory required.

    And from here

    The result of all this magic is that you can largely ignore the distinction between int and Integer, with a few caveats. An Integer expression can have a null value. If your program tries to autounbox null, it will throw a NullPointerException. The == operator performs reference identity comparisons on Integer expressions and value equality comparisons on int expressions. Finally, there are performance costs associated with boxing and unboxing, even if it is done automatically

提交回复
热议问题