No, this is not safe at all. The == operator compares links, not values.
Using == works for integers from -128 to 127, but not for other integers. The following code demonstrates that == does not always work:
Integer a = Integer.valueOf(10); Integer b = Integer.valueOf(10); System.out.println(a == b); true Integer c = Integer.valueOf(1000); Integer d = Integer.valueOf(1000); System.out.println(c == d); false
See how it works on the Internet: ideone
The explanation for this behavior is the implementation of Integer.valueOf :
public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) {
a source
In addition, the standard requires that box integers for small inputs (from -128 to 127) produce objects with equal references.
5.1.7 Boxing Conversion
If the p value in the box is true, false, bytes, and a char in the range from \ u0000 to \ u007f or int or short number between -128 and 127, then let r1 and r2 be the result of any two box conversions on page. It always happens such that r1 == r2.
However, the standard does not provide such guarantees for integers outside this range.
In general, is it good to compare two references to an immutable class that are created by calling the same static factory method using == instead of equals?
As shown above, it does not work at all. But if you guarantee that two immutable objects with the same value always have the same reference, then yes, that might work. However, there are some rules that you must follow:
- The constructor should not be publicly available.
- Each object created using the static method must be cached.
- Each time you are asked to create an object, you must first check the cache to make sure that you have already created the object with the same value.