比较Java中的Character,Integer和类似类型:使用equals还是==? [英] Comparing Character, Integer and similar types in Java: Use equals or ==?

查看:732
本文介绍了比较Java中的Character,Integer和类似类型:使用equals还是==?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确定Java中的某些内容:
如果我有一个字符或一个整数或一个Long以及那些东西,我应该使用equals还是==足够?

I wanted to make sure about something in Java: If I have a Character or an Integer or a Long and those sort of things, should I use equals or is == sufficient?

我知道使用字符串并不能保证每个唯一字符串只有一个实例,但我不确定其他盒装类型。

I know that with strings there are no guarantees that there is only one instance of each unique string, but I'm not sure about other boxed types.

我的直觉是使用等于,但我想确保我不浪费表现。

My intuition is to use equals, but I want to make sure I'm not wasting performance.

推荐答案

编辑:规范为装箱转换提供一些保证。来自第5.1.7节

The spec makes some guarantees for boxing conversions. From section 5.1.7:


如果盒装的值为真,
false,一个字节,
\范围内的一个字符u0000到\ u007f,或-128到127之间的int或短
数,然后让
r1和r2为p的任意两个
拳击转换的结果。 r1 == r2的情况总是

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

实现可以使用更大的游泳池,请注意。

The implementation can use a larger pool, mind you.

我会真的避免编写依赖于此的代码。不是因为它可能会失败,而是因为它并不明显 - 很少有人能够很好地了解规范。 (我之前认为它是依赖于实现的。)

I would really avoid writing code which relies on that though. Not because it might fail, but because it's not obvious - few people will know the spec that well. (I previously thought it was implementation-dependent.)

您应该使用等于或比较基础值,即

You should use equals or compare the underlying values, i.e.

if (foo.equals(bar))

if (foo.intValue() == bar.intValue())

请注意,即使自动装箱保证使用固定值,其他来电者也可以随时创建无论如何,实例。

Note that even if the autoboxing were guaranteed to use fixed values, other callers can always create separate instances anyway.

这篇关于比较Java中的Character,Integer和类似类型:使用equals还是==?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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