Java Reference
In-Depth Information
compiler might be able to avoid some of the autoboxing and unboxing operations,
but in general looping operations should be done with primitive types unless there
is a
very
good reason to use a wrapper type.
Where autoboxing and unboxing
should
be used is whenever an explicit con-
version to or from a wrapper type would be required if you were using J2SE 1.4.
In 5.0 and above, just write the code “naturally” and let the compiler handle
the conversions automatically. But don't go out of your way to demonstrate the
automatic conversion feature as we did in the examples above.
Autoboxing and unboxing also work with
Boolean
and
boolean
types. For
example,
boolean one
=
true; // nothing new here
Boolean two
=
true; // autoboxing of boolean literal
"
true
"
// to Boolean type
if (one && two)
// auto unboxing
do
-
something ();
Before 5.0, the
if
,
while
, and
do-while
statements (see Chapter 2) all
expected
boolean
expressions. Through the use of unboxing, those flow control
statements now also accept expressions that evaluate to
Boolean
types. Simi-
larly, the old
switch
statement expects a
byte
,
short
,
int
,or
char
type in
Java 1.4 and below. With the addition of autoboxing in 5.0,
switch
now also
accepts
Byte
,
Short
,
Integer
, and
Character
types.
Where autoboxing and unboxing become particularly useful is with the inser-
tion and retrieval of primitive values into and out of object containers like
Vector
and
ArrayList
(see Chapter 10). Since the container classes only accept
objects, not primitives, prior to J2SE 5.0 it was necessary to convert primi-
tives to wrapper object types for insertion and to convert wrapper objects back
to primitives after retrieval. Autoboxing and unboxing now make these opera-
tions almost transparent. With the additional new “generics” feature in 5.0, using
primitives with container objects is even simpler. We postpone that discussion
until we discuss the generics feature in Chapter 10.
3.7.3 Autoboxing and overloading
Autoboxing and unboxing can make method overloading interesting. Consider
the two overloaded methods shown here:
long method1 (long l) {return l+1;}
long method1 (Integer i) {return i+2;}
If you call
method1()
with a primitive
long
parameter, then the first
method1()
is used. If you call
method1()
with an
Integer
object parameter,
then the second
method1()
is used. There is nothing new there. But what hap-
pens if you call
method1()
with an
int
parameter? In J2SE 1.4 and below, the
int
is promoted to a
long
and the first
method1()
is used. With autoboxing, it
Search WWH ::
Custom Search