Java Reference
In-Depth Information
The elements in a Vector are accessed by using an index, just like array ele-
ments. The elements also must be of type java.lang.Object, which means that
the only elements that cannot appear in a Vector are the eight primitive data
types.
If you want to add a primitive data type to a Vector, use its corresponding
wrapper class found in the java.lang package. For example, if you want to
add an int to a Vector, wrap the int in an Integer object and add the
Integer object to the Vector.
A Vector has two attributes: a capacity and a capacity increment. The capac-
ity represents the size of the Vector in memory. After the capacity is reached,
the Vector must grow before a new element can be added. The capacity incre-
ment denotes how much the Vector should grow by when the Vector needs to
increase in size. If the capacity increment is 0, the array simply doubles in
capacity each time it needs to grow.
For example, if a Vector has a capacity of 50 and a capacity increment of 10,
the Vector does not need to grow in memory until after 50 elements are added.
When the 51st element is added, the Vector will grow to size 60 because its
capacity increment is 10.
The Vector class has four constructors:
public Vector(). Creates an empty Vector with an initial capacity of 10
and a capacity increment of 0.
public Vector(int initialCapacity). Creates an empty Vector with the
given initial capacity and a capacity increment of 0.
public Vector(int initialCapacity, int capacityIncrement). Creates an
empty Vector with the given initial capacity and capacity increment.
public Vector(Collection c). Creates a Vector that initially contains the
elements in the given Collection. Collection is an interface that all of the
data structures in the collections framework have in common. This con-
structor allows you to create a new Vector from the elements stored in a
hash table or tree, for example, because the hash table or tree will be of
type Collection through polymorphism.
The following statement instantiates an empty Vector with an initial capac-
ity of 50 and a capacity increment of 10:
Vector employees = new Vector(50, 10);
The employees Vector is initially empty, so its size is 0. Elements are added
to the Vector by using the various methods in the Vector class, which we will
discuss next.
Search WWH ::




Custom Search