Java Reference
In-Depth Information
Size and capacity are two entirely different attributes of a Vector. The size
of a Vector is the number of elements in the Vector. The capacity of a
Vector is the amount of room available for adding elements before the
Vector needs to grow. For example, the employees Vector is empty, so its
size is 0. However, it has room for 50 objects, so its capacity is 50.
Adding Elements to a Vector
The following methods from the Vector class are used to add elements to a Vec-
tor. Keep in mind that Vectors are similar to arrays, and each element is asso-
ciated with an index in the array. Also notice that there are some redundancies
in the functionality of some of these methods, which was done to make the
Vector class similar to the other classes in the collections framework. (The Vec-
tor class has been around since JDK 1.0, whereas the collections framework is
new as of Java 2.)
public void add(int index, Object element).
Inserts the Object at the
specified index within the Vector.
public boolean add(Object element). Appends the Object to the end of
the Vector. The method returns true if the element is added successfully.
public void addElement(Object element). Appends the Object to the
end of the Vector and is identical to the add(Object) method.
public void insertElementAt(Object element, int index). Inserts the
Object at the specified index, causing elements after the index to be
shifted down one index spot in the Vector. This method is identical to
the add(int, Object) method.
public boolean addAll(Collection c). Adds the elements in the given
Collection to the end of the Vector and returns true if the Vector
changed.
public boolean addAll(int index, Collection c). Adds the elements in the
given Collection to the Vector at the specified index and returns true if
the Vector changed.
The VectorDemo program, shown in the following listing, creates a Vector of
capacity 50 and capacity increment 10. Then, a for loop randomly inserts 51
Employee objects. Study the program carefully and try to determine not only
the output of the program, but what the Vector will look like at the end of the
for loop.
import java.util.Vector;
public class VectorDemo
{
Search WWH ::




Custom Search