问题描述
例如:
Long objectLong = 555l;
long primitiveLong = 555l;
System.out.println(objectLong == primitiveLong); // result is true.
有没有调用objectLong.longValue()方法比较Long到long或者其他方式? / p>
Is there invocation objectLong.longValue() method to compare Long to long or maybe some other way?
推荐答案
和以往一样,Java语言规范是合适的资源。
As ever, the Java Language Specification is the appropriate resource to consult
从(Numerical Equality Operators == and!=):
From JLS 15.21.1 ("Numerical Equality Operators == and !="):
请注意,二进制数字促销会执行价值集转换(§5.1.13),并可能执行取消转换转换(§5.1.8)。
Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).
然后从(二进制数字促销):
Then from 5.6.2 (binary numeric promotion):
- 如果任何操作数是引用类型,
$ b
$ b
因此 Long
被取消装箱为 long
。您的代码等效于:
So the Long
is unboxed to a long
. Your code is equivalent to:
Long objectLong = 555l;
long primitiveLong = 555l;
// This unboxing is compiler-generated due to numeric promotion
long tmpLong = objectLong.longValue();
System.out.println(tmpLong == primitiveLong);
这篇关于如何比较对象和原语,与operator ==在Java工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!