Skip to main content

Section 9.10 From the Java Library: java.util.Vector

The java.util.Vector class implements an array of objects that can grow in size as needed. One limitation of regular arrays is that their lengths remain fixed. Once the array is full — once every element is used — you can't allocate additional elements.

Figure 9.10.1. The Vector class.

The Vector class contains methods for storing and retrieving objects, and for accessing objects by their index position within the Vector(Figure 9.10.1).

One use for a Vector would be when a program needs to store input from the user or a file without knowing in advance how many items there are. Using a Vector is less efficient than an array in terms of processing speed, but it gives you the flexibility of growing the data structure to meet the storage requirements.

As an illustration of this idea, the program in Listing 9.10.2 creates a random number of integers and then stores them in a Vector. The Vector, which is declared and instantiated in main(), is initially empty. Integers from 0 to the random bound are then inserted into the Vector. In this case, insertions are done with the addElement() method, which causes the Vector object to insert the element at the next available location, increasing its size, if necessary.

import java.util.Vector;
public class VectorDemo {
  
  public static void printVector(Vector v) {
    for (int k=0; k < v.size(); k++)
      System.out.println(v.elementAt(k).toString());
  } // printVector()
  
  public static void main(String args[]) {
    Vector vector = new Vector();  // An empty vector
    int bound = (int)(Math.random() * 20);
    for (int k = 0; k < bound; k++ )   // Insert a random
      vector.addElement(new Integer(k));// number of Integers
    printVector(vector);            // Print the elements
  } // main()
} // VectorDemo
Listing 9.10.2. Demonstration of the Vector class.

Once all the integers have been inserted, the printVector() method is called. Note that it uses the size() method to determine how many elements the Vector contains. This is similar to using the length() method to determine the number of characters in a String.

Finally, note that a Vector stores objects. It cannot be used to store primitive data values. You cannot store an int in a Vector. Therefore, we need to use the Integer wrapper class to convert ints into Integers before they can be inserted into the Vector. Because you can't just print an Integer, or any other Object, the toString() method is used to print the string representation of the object.

By defining Vector to store Object s, Java's designers have made it as general as possible and, therefore, as widely useful as possible.

You have attempted of activities on this page.