Java Reference
In-Depth Information
This is not an efficient add because all subsequent elements in the employ-
ees Vector must shift down one to make room for the new employee. The
Hourly objects are added to the Vector using the following statement:
employees.insertElementAt(e, numSalary);
The same result could have been achieved by using the following statement:
employees.add(numSalary, e);
The numSalary value is the number of Salary objects already added to the
Vector, so the Hourly objects are inserted somewhere in the middle of the
employees Vector.
The Contractor objects are added to the Vector by using the following
statement:
employees.add(e);
This appends the Contractor object to the end of the employees Vector. The
result is a Vector of 51 Employee objects with the Salary objects appearing at
the beginning, the Hourly objects in the middle, and the Contractor objects at
the end. This means that the size of employees is 51, because 51 objects were
added. Because its capacity was initially 50, employees needed to grow once
by its capacity increment of 10, so the capacity of employees is 60, as shown by
the output of the VectorDemo program shown in Figure 9.8.
Accessing and Removing Elements in a Vector
Elements can be removed from a Vector, which causes the remaining elements
to move up one (subtracting one from their index) in the Vector to fill in the
space made by the removed element. The Vector class contains the following
methods for removing elements:
Figure 9.8
Output of the VectorDemo program.
Search WWH ::




Custom Search