The values of boxed primitives cannot be directly compared using the ==
and !=
operators because they compare object references, not object values. Programmers could 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.
Wiki Markup |
---|
Autoboxing automatically wraps a value of a primitive type with the corresponding wrapper object. The [Section 5.1.7 "Boxing Conversion,"|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7] of the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\] explains which primitive values are memoized during autoboxing: |
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
.
...