Java Reference
In-Depth Information
Wrapper Class
A class that “wraps” (stores) primitive data as an object.
To understand the role of a wrapper class, think of a piece of candy packaged in a
wrapper. Pieces of candy can be sticky and inconvenient to handle directly, so we put
them inside wrappers that make handling them more convenient. When we want to
eat the actual candy, we open up the wrapper to get the candy out. The Java wrapper
classes fill a similar role.
For example, consider simple integers, which are of type
int
, a primitive type.
Primitive types are not objects, so we can't use values of type
int
in an object con-
text. To allow such use, we must wrap up each
int
into an object of type
Integer
.
Integer
objects are very simple. They have just one field: an
int
value. When we
construct an
Integer
, we pass an
int
value to be wrapped; when we want to get the
int
back, we call a method called
intValue
that returns the
int
.
To understand the distinction between
int
and
Integer
, consider the following
variable declarations:
int x = 38;
Integer y = new Integer(38);
This code leads to the following situation in memory:
x38
y
value
38
Primitive data is stored directly, so the variable
x
stores the actual value
38
.
Objects, by contrast, are stored as references, so the variable
y
stores a reference to
an object that contains
38
.
If we later want to get the
38
out of the object (to unwrap it and remove the candy
inside), we call the method
intValue
:
int number = y.intValue();
The wrapper classes are of particular interest in this chapter because when you use
an
ArrayList<E>
, the
E
needs to be a reference type. You can't form an
ArrayList<int>
, but you can form an
ArrayList<Integer>
. For example, you
can write code like the following that enters several integer values into a list and adds
them together:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(13);
list.add(47);
list.add(15);
list.add(9);
Search WWH ::
Custom Search