...
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 Care should be taken during this process, especially when performing comparisons. The Java Language Specification Section 5.1.7 Boxing Conversion explains this point clearlywhich values can be safely compared:
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 |
---|
This noncompliant code example (adopted from \[[Bloch 2009|AA. Bibliography#Bloch 09]\]), defines a {{Comparator}} with a {{compare()}} method. The {{compare()}} method accepts two boxed primitives as arguments. |
...
To be compliant, use any of the four comparison operators <
, >
, <=
and >=
since these force the values to be automatically unboxed. The ==
and !=
operators should not be used to compare boxed primitives.
...