The values of boxed primitives cannot be directly compared using the ==
and !=
operators because these operators compare object references rather than object values. Programmers can find this behavior surprising because autoboxing memoizes, or caches, the values of some primitive variables. Consequently, reference comparisons and value comparisons produce identical results for the subset of values that are memoized.
Autoboxing automatically wraps a value of a primitive type with the corresponding wrapper object. The _Java Language Specification_ (JLS) [§5§5.1.7, "Boxing Conversion,"|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7] \ [[JLS 2005|AA. References#JLS 05]\], explains which primitive values are memoized during autoboxing: Wiki Markup
If the value
p
being boxed istrue
,false
, abyte
, achar
in the range\u0000
to\u007f
, or anint
orshort
number between-128
and127
, then letr1
andr2
be the results of any two boxing conversions ofp
. It is always the case thatr1 == r2
.
...
Noncompliant Code Example
...
This noncompliant code example defines a {{Comparator
}} with a {{compare()
}} method \[ [Bloch 2009|AA. References#Bloch 09]\]. The {{compare()
}} method accepts two boxed primitives as arguments. The {{==
}} operator is used to compare the two boxed primitives. In this context, however, it compares the _references_ to the wrapper objects rather than comparing the _values_ held in those objects.
Code Block | ||
---|---|---|
| ||
static Comparator<Integer> cmp = new Comparator<Integer>() { public int compare(Integer i, Integer j) { return i < j ? -1 : (i == j ? 0 : 1); } }; |
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP03-J | low | likely | medium | P6 | L2 |
Automated Detection
Detection of all uses of the reference equality operators on boxed primitive objects is straightforward. Determining the correctness of such uses is infeasible in the general case.
...
CWE-595. Comparison of object references instead of object contents | |
| CWE-597. Use of wrong operator in string comparison |
Bibliography
...
[[Bloch 2009AA. References#Bloch 09]] | 4, Searching for the One | ]]></ac:plain-text-body></ac:structured-macro> | <ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f82ec418-7939-4d3b-b767-680a43221f06"><ac:plain-text-body><![CDATA[ | |
[[JLS 2005AA. References#JLS 05]] | http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7] | ]]></ac:plain-text-body></ac:structured-macro> | <ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f8847edf-f4db-4780-b9d6-3d1cd8655110"><ac:plain-text-body><![CDATA[ | |
[[Pugh 2009AA. References#Pugh 09]] | Using == to Compare Objects Rather than |
...
EXP02-J. Use the two-argument Arrays.equals() method to compare the contents of arrays 02. Expressions (EXP) EXP04-J. Ensure that autoboxed values have the intended type