我想知道下一个代码片段的内部Java行为是什么:
Long a = 123L;
long b = 123;
System.out.println("a equals b?: " + (a == b));
结果是正确的,虽然比较两个Long对象将是假的(因为它比较了它们的引用).是Java将Long对象转换为原始值,因为检测==运算符对另一个原始对象?
解决方法:
It is Java converting Long object into its primitive value because detects == operator against another primitive object?
是.其中一个操作数是基本类型,另一个操作数可通过拆箱转换为基元.
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).
Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).
此外,重要的是要注意,仅当两个操作数都是对象时才执行引用相等性. JLS section 15.21.3说:
If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.
标签:java,comparison,long-integer
来源: https://codeday.me/bug/20190611/1220921.html