12. Arrays and Array Processing

12.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.

The Vector class contains methods for storing and retrieving ob- jects, and for accessing objects by their index position within the Vector (Fig. 9.27).

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 Figure 9.28 creates a ran- dom 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.

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 Objects, Java’s designers have made it as Vectors store objects

general as possible and, therefore, as widely useful as possible.