4.10 Using Vectors in Java

Once we create an array we cannot change its size. Vectors, on the other hand, can grow and shrink at runtime as required. A Vector is an object of the java.util.Vector class. A Vector object is created using the new keyword, for example,

Vector vlist = new Vector();

This creates a Vector object, vlist, with default capacity of ten elements. As soon as 10 elements have been added, the capacity, by default, will be doubled to 20 elements in total.
It is possible to specify other capacities and increment factors. To add an element to an array, use the java.util.Vector.add method. This method allows you to add any object to the end of the Vector, for example,


vlist.add(''ABC");

adds string "ABC", which is an object, to the end of Vector vlist. The java.util.Vector class provides methods capacity, which returns the current capacity of a Vector, and size, which returns the number of elements in the Vector. There are also methods for returning or deleting elements at a given position in the Vector.

Since Java version 1.2, a Vector is actually an implementation of the List interface, which in turn, is a derivation of the Collection interface.

Note that a Vector can only hold object types. We cannot directly add a primitive data type, such as int, to a Vector. If we do need to add a primitive to a Vector, we must first convert it to an object using an object wrapper.

No comments:

Post a Comment