Java Reference
In-Depth Information
As described in the preceding section, every element of a
Vector
object is a reference.
Therefore, to create a
Vector
of, say integers, the integers must be wrapped in an
object. Recall that Java provides a wrapper class corresponding to each primitive data
type. For example, the wrapper class corresponding to type
int
is
Integer
. Therefore,
an
int
value can be wrapped in an
Integer
object. As explained in Chapter 6,
as of Java 5.0, Java has simplified the wrapping and unwrapping of primitive
type values, called the autoboxing and auto-unboxing of primitive data types. For example,
suppose that
x
is an
int
variable and
num
is an
Integer
object.
Consider the statements:
num = 25;
num =
new
Integer(25);
After the execution of either of these statements,
num
would point to an
Integer
object
with the value
25
. Recall that the expression,
num = 25;
, is called the autoboxing of the
int
type.
Next, we illustrate how to create a
Vector
of
Integer
objects to store
int
values.
Suppose that you have the declaration:
Vector<Integer> list =
new
Vector<Integer>();
The following statements create
Integer
objects with the
int
values
13
and
25
(if there
are no other
Integer
objects with these values), and the
Integer
objects are assigned to
list
:
list.addElement(13);
list.addElement(25);
You can use other
Vector
operations to manipulate the objects of
list
. The program
IntVectorExample.java
, which shows how to create and manipulate a
Vector
of
Integer
objects, can be found with the Additional Student Files at www.cengagebrain.com.
Also, recall that the wrapper class corresponding to type
char
is
Character
, type
double
is
Double
, type
float
is
Float
, and type
boolean
is
Boolean
.
Recall that a foreach loop can be used to process the elements of a collection object one
at a time. Because each
Vector
object is a collection of elements, you can use a foreach
loop to process the elements of a
Vector
object. The syntax to use this type of
for
loop
to process the elements of a
Vector
object is:
for
(type identifier : vectorObject)
statements
Search WWH ::
Custom Search