java character 比较,比较Java中的Character,Integer和类似类型:使用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.

解决方案

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

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

or

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值