Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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:

  1. all values involved in the comparison are primitive types (and preferably not floating point numbers)
  2. you really want to know if two references refer to the same object (this includes comparison of enums, because there the value is bound to the object identity)
//Quick test
public class Test {
  public static void main(String[] args) {
    System.out.println("Are they equal? "+ (new Long(5) == new Long(5)));
  }
}

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:

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.

and:

Discussion

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly.

For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.

This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all characters and shorts, as well as integers and longs in the range of -32K - +32K.

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.

Implementations of the equals(Object o) method almost always start with

if(this == o) return true;

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.

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

I like to see the result visually:

  public static void main(String[] args)
  {
        Integer a = 126; //no boxed up conversion, new object ref
        Integer b = 126; //no boxed up conversion, re-use memory address
        System.out.println("Are they equal? " + (a == b)); // true
        Integer a1 = 140; //boxed up conversion, new object
        Integer b1 = 140; //boxed up conversion, new object
        System.out.println("Are they equal? " + (a1 == b1)); // false
        System.out.println("Are they equal? " + (new Long(5) == new Long(5))); // false
  }

== compares the object reference while equals(Object obj) compares for object equality. If there can ever be more than one instance of an equals object in existence then you must use equals for equality comparison.

Examples:

Integer i1 = new Integer(12345);
Integer i2 = new Integer(12345);

these are different object instances but are equal according to Integer's equality, so you must use equals(Object obj)

public enum Gender {
    MALE, FEMALE;
}

in this case there will only be one instance of FEMALE in existence so == is safe to use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top