Java Reference
In-Depth Information
Converting a primitive value to a wrapper object is known as a boxing
conversion; unsurprisingly, extracting a primitive value from a wrapper
object is known as an unboxing conversion. [1] The details of these con-
versions are discussed in " Boxing Conversions " on page 198 . These
automated conversions make it easy to write general purposes classes
that are written in terms of Object references, but that can handle either
reference types or primitive types. The HashMap class, for example, stores
only references, not primitive typessee " HashMap " on page 590 but an
int can be passed as a key because it will be converted to an Integer
instance:
[1] This difference in terminology ("wrap" versus "box") is an historical artifact.
int key = ... ;
map.put(key, value);
The efficiency and convenience of using an int can be maintained, while
an object can still be obtained when necessarythe best of both worlds.
A second purpose of the wrapper classes is to provide a home for meth-
ods and variables related to the type (such as string conversions and
value range constants). Here, for example, is how you might check
whether you could use a faster float calculation on a particular value or
whether the value requires a larger range than a float provides and so
must be performed as a double calculation:
double aval = Math.abs(value);
if (Float.MAX_VALUE >= aval && aval >= Float.MIN_VALUE)
return fasterFloatCalc((float) value);
else
return slowerDoubleCalc(value);
The following sections cover methods and constants specific to each par-
ticular wrapper class, but first let's look at some things that are common
to most of the wrapper classes.
 
 
Search WWH ::




Custom Search