Is it guaranteed that new Integer(i) == i in Java?

后端 未结 2 920
盖世英雄少女心
盖世英雄少女心 2020-11-27 20:20

Consider the following snippet:

    int i = 99999999;
    byte b = 99;
    short s = 9999;
    Integer ii = Integer.valueOf(9); // should be within cache

           


        
2条回答
  •  一向
    一向 (楼主)
    2020-11-27 20:56

    Yes. JLS §5.6.2 specifies the rules for binary numeric promotion. In part:

    When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:

    If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed.

    Binary numeric promotion applies for several numeric operators, including "the numerical equality operators == and !=."

    JLS §15.21.1 (Numerical Equality Operators == and !=) specifies:

    If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

    In contrast, JLS §15.21.3 (Reference Equality Operators == and !=) provides:

    If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality

    This fits the common understanding of boxing and unboxing, that's it only done when there's a mismatch.

提交回复
热议问题