如何比较对象和原语,与operator ==在Java工作? [英] How comparison Object and primitive, with operator == works in Java?

查看:155
本文介绍了如何比较对象和原语,与operator ==在Java工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

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

From JLS 15.21.1 ("Numerical Equality Operators == and !="):


如果相等运算符的操作数都是数字类型,或一个是数字类型,另一个是可转换(§5.1.8)为数字类型,在操作数(§5.6.2)上执行二进制数字促销。

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).

请注意,二进制数字促销会执行价值集转换(§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).

然后从 5.6。 2 (二进制数字促销):

Then from 5.6.2 (binary numeric promotion):


当运算符将二进制数字促销应用于一对操作数时,表示可转换为数字类型的值,以下规则适用:

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:


  • 如果任何操作数是引用类型,

$ 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工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆