In the absence of autoboxing, the values of boxed primitives cannot be compared using the ==
and !=
operators by default. This is because these are interpreted as reference comparison operators. This condition is demonstrated in the first noncompliant code example.
Autoboxing on the other hand, can also produce subtle effects. It works by automatically wrapping the primitive type to the corresponding wrapper object. Some care should be taken during this process, especially when performing comparisons. The Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\] explains this point Specification Section 5.1.7 Boxing Conversion explains this point clearly: 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
.
...
Wiki Markup |
---|
\[[Bloch 2009|AA. Bibliography#Bloch 09]\] 4. "Searching for the One"
\[[JLS 2005|AA. Bibliography#JLS 05]\] Section 5.1.7, "Boxing Conversion"
\[[Pugh 2009|AA. Bibliography#Pugh 09]\] Using == to compare objects rather than .equals |
...