The values of boxed primitives cannot be directly compared using the ==
and !=
operators , because these operators are reference comparison operators. Programmers may could find this surprising, however, because autoboxing memoizes the values of some primitive values. 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 as because they are appropriately autoboxed at the call site.
...
To be compliant, use any of the four comparison operators, <
, >
, <=
and , or >=
since , because these cause automatic unboxing of the primitive values. The ==
and !=
operators should not be used to compare boxed primitives.
...
If the JLS specified the range of memoized integer values as -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 intended. Because 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 requires that all values encountered fall within that range. A built-in dependence on "knowledge" of the specific value ranges that may could be encountered is unreliable in the face of future changes to the code.
...
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 objects are guaranteed to be singletons.
...
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.
...