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.
Output:
"Are they equal? 0"
Answer:
No, they're not equal. You must use .equals or compare their primitive values.
Java Language Spec 5.1.7:
and:
So, in some cases == will work, in many others it will not. Always use .equals to be safe since you cannot grantee (generally) how the instances were obtained.
If speed is a factor (most .equals start with an == comparison, or at least they should) AND you can gurantee how they were allocated AND they fit in the above ranges then == is safe.
Some VMs may increase that size, but it is safer to assume the smallest size as specified by the langauge spec than to rely on a particular VM behaviour, unless you really really really need to.
EDIT: The spec makes some guarantees for boxing conversions. From section 5.1.7:
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.or
Note that even if the autoboxing were guaranteed to use fixed values, other callers can always create separate instances anyway.