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.
==
compares the object reference whileequals(Object obj)
compares for object equality. If there can ever be more than one instance of an equals object in existence then you must useequals
for equality comparison.Examples:
these are different object instances but are equal according to Integer's equality, so you must use
equals(Object obj)
in this case there will only be one instance of
FEMALE
in existence so==
is safe to use.If you want to compare anything about the value of any object, use
.equals()
.Even (and especially) if those Objects are the primitive wrapper types Byte, Character, Short, Integer, Long, Float, Double and Boolean.
"
==
" only ever compares the object identity and you that's very, very rarely what you want. And de-facto never what you want with the primitive wrappers.Only use
==
in one of those two scenarios:enum
s, because there the value is bound to the object identity)Implementations of the equals(Object o) method almost always start with
so using
equals
even if==
is true is really not much of a performance hit.I recommend always* using the
equals
method on objects.* of course there are a very few times when you should not take this advice.
I like to see the result visually:
The general answer is no, you are not guaranteed that for the same numeric value, the Long objects you get are the same (even if you restrict yourself to using Long.valueOf()).
However, it is possible that you would get a performance improvement by first trying to test the equality of references (using ==) and then, if failed, trying equals(). It all hinges on the comparative costs of the additional == test and the method call... Your mileage may vary, but it is worth trying a simple loop test to see which is better.
It is worth noting that auto-boxed values will uses pooled object if they are available. This is why (Integer) 0 == (Integer) 0 but (Integer) 128 != (Integer) 128 for Java 6u13