Consider two references of type Integer that call the static factory method valueOf as shown below:-
Integer a = Integer.valueOf("10");
Integer b = Integer.valueOf("10");
Considering that Integer is immutable, is it ok to compare a and b using == instead of using equals method. I am guessing that the valueOf method makes sure that only one instance of Integer with the value 10 is created and a reference to this instance is returned for every Integer created with a value 10.
In general, is it ok to compare two references of an immutable class that are created using a call to the same static factory method by using == instead of equals?
Edit:
The Integer class was used just as an example. I am aware thar Intgers upto 127 will return true if they are compared using ==. What i need to know is that when l create my own immutable class, say MyImmutable with a method create() that will ensure that no duplicate MyImmutable objects are created, will it be ok if I compare 2 MyImmutable references created using the create method by using == instead of equals.
No, that’s not safe in general. The
==operator compares the references, not the values.Using
==happens to work for integers between -128 and 127, but not for other integers. The following code demonstrates that==won’t always work:See it working online: ideone
The explanation for this behaviour lies in the implementation of
Integer.valueOf:source
Not also that the standard requires that boxing integers for small inputs (-128 to 127) gives objects with equal references.
However the standard makes no such guarantees for integers outside this range.
As shown above, it won’t work in general. But if you ensure that two immutable objects with the same value always have the same reference, then yes, it could work. However there are some rules you must follow carefully: