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.
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.
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 int
s into Integer
s 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.
Principle 9.10.3. EFFECTIVE DESIGN: Generality.
Defining a data collection, such as an array or a Vector
, in terms of the Object
class makes it capable of storing and processing any type of value, including values of primitive data types. This is because the Object
class is the root of the Java class hierarchy.