The values of boxed primitives cannot be directly compared using the ==
and !=
operators because these operators are reference comparison operatorsthey compare object references, not object values. Programmers could find this surprising , however, because autoboxing memoizes the values of some primitive valuesvariables. Consequently, reference comparisons and value comparisons produce identical results for the subset of values that are memoized.
...
Wiki Markup |
---|
This noncompliant code example (\[[Bloch 2009|AA. Bibliography#Bloch 09]\]), defines a {{Comparator}} with a {{compare()}} method. The {{compare()}} method accepts two boxed primitives as arguments. The problem is the use of the {{==}} operator to compare the two boxed primitives; in this context, it compares the _references_ to the wrapper objects rather than comparing the _values_ held in those objects. By comparison, the {{\<}} operator causes automatic unboxing of the primitive values and, consequently, operates as expected. |
Code Block | ||
---|---|---|
| ||
static Comparator<Integer> cmp = new Comparator<Integer>() { public int compare(Integer i, Integer j) { return i < j ? -1 : (i == j ? 0 : 1); } }; |
Note that primitive integers are also accepted by this declaration because they are appropriately autoboxed at the call site.
Compliant Solution
To be compliant, use any of the four This compliant solution uses the comparison operators, <
, >
, <=
, or >=
, because these cause automatic unboxing of the primitive values. The ==
and !=
operators should not be used to compare boxed primitives.
...
Noncompliant Code Example
This noncompliant code example uses the ==
operator to compare two Integer
objects. According to the guideline EXP01-J. Do not confuse abstract object equality with reference equality, in order for the ==
operator to return true
for two object references, they must point to the same underlying object. Results of using the ==
operator in this case will be misleading.
Code Block | ||
---|---|---|
| ||
public class Wrapper { public static void main(String[] args) { Integer i1 = 100; Integer i2 = 100; Integer i3 = 1000; Integer i4 = 1000; System.out.println(i1 == i2); System.out.println(i1 != i2); System.out.println(i3 == i4); System.out.println(i3 != i4); } } |
These comparisons generate This program prints the output sequence: true
, false
, false
and true
. The cache in the Integer
class memoizes integer values from -127
to 128
only, which explains accounts for the output of the above code. Avoid this problem by using the equals()
method instead of the ==
operator to compare wrapper classes. See guideline EXP01-J for further details.
Compliant Solution
This compliant solution uses object1.the equals(
object2)
method to compare the values of the objects. The results are program now prints true
, false
, true
and false
, as expected.
Code Block | ||
---|---|---|
| ||
public class Wrapper { public static void main(String[] args) { Integer i1 = 100; Integer i2 = 100; Integer i3 = 1000; Integer i4 = 1000; System.out.println(i1.equals(i2)); System.out.println(!i1.equals(i2)); System.out.println(i3.equals(i4)); System.out.println(!i3.equals(i4)); } } |
Noncompliant Code Example
Java Collections contain only objects; they cannot contain primitive types. Further, the type parameters of all Java generics must be object types rather than primitive types. That is, attempting to declare an ArrayList<int>
(which would presumably contains values of type int
) fails at compile time because type int
is not an object type. An important The appropriate declaration would be ArrayList<Integer>
, which makes use of the wrapper classes and autoboxing is to store integer values in an ArrayList<Integer>
instance.
This noncompliant code example attempts to count the number of integers indices in arrays list1
and list2
that have corresponding equivalent values. Recall that class Integer
memoizes must memoize only those integer values in the range -127 to 128; it returns might return non-unique objects for all values outside that range. Consequently, when comparing autoboxed integer values outside that range, the ==
operator returns might return {{false}, and the output of this example is could be 0.
Code Block | ||
---|---|---|
| ||
public class Wrapper { public static void main(String[] args) { // Create an array list of integers, where each element // is greater than 127 ArrayList<Integer> list1 = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list1.add(i + 1000); } // Create another array list of integers, where each element // has the same value as the first list ArrayList<Integer> list2 = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list2.add(i + 1000); } // Count matching values. int counter = 0; for (int i = 0; i < 10; i++) { if (list1.get(i) == list2.get(i)) { counter++; } } // print the counter: 0 in this example System.out.println(counter); } } |
If the JLS specified the range of particular JVM running this code memoized integer values as from -32768 to 32767, for example, all of the int
values in the example would have been autoboxed to singleton Integer
objects and the example code would have operated as intendedexpected. Because Using reference equality and value equality produce the same result only for values within the range of memoized values, and, because that range is necessarily limited, successfully using reference equality in place of value equality instead of object equality requires that all values encountered fall within that range. A built-in dependence on "knowledge" of the specific value ranges that could be encountered is unreliable in the face of future changes to the codethe interval of values memoized by the JVM. The JLS does not specify this interval; it only provides a minimum range. Consequently, successful prediction of this program's behavior would require implementation-specific details of the JVM.
Compliant Solution
This compliant solution uses the equals()
method to perform value comparisons of wrapped objects. It produces the correct output 10.
...
EXP03-EX1: The values of autoboxed Boolean
variables may be compared using the reference equality operators because the Java language guarantees that the autoboxing yields either Boolean.True
or Boolean.False
(as appropriate); these . These objects are guaranteed to be singletons.
Code Block | ||
---|---|---|
| ||
Boolean b1 = true; // Or Boolean.True Boolean b2 = true; // Or Boolean.True if(b1 == b2); { // always equal // ... } always equal |
Note, however, that the constructors for class Boolean
return distinct newly-instantiated objects. Using the reference equality operators in place of value comparisons will yield unexpected results in this case.
Code Block | ||
---|---|---|
| ||
Boolean b1 = new Boolean("true"); Boolean b2 = new Boolean("true"); if (b1 == b2); { // never equal // ... } |
EXP03-EX2 Use the reference equality operators (==
and !=
) to compare references.
never equal
|
Risk Assessment
Using the equal and not equal equivalence operators to compare values of boxed primitives can lead to erroneous comparisons.
...