Java Reference
In-Depth Information
d.add( new Integer(4));
The argument of a call to add is the object to be added. It cannot be a value of a
primitive type; elements of Vector s are objects. That is why we used an instance
of wrapper class Integer as the argument of the first call of add . If you are not
familiar with class Integer , study Sec. 5.1 on wrapper classes.
A two-parameter add procedure can be used to insert an object anywhere in
the Vector . Suppose Vector d is as in Fig. 5.3. Then execution of
d.add(1, "yellow");
changes d to contain this list of objects:
4 , "yellow" , "red" , "blue"
We use our non-Java notation for Vector s to describe this procedure: The call
d.add(k, obj);
changed Vector d to contain the list of values d[0..k-1] , obj , d[k..] .
The call d.add(k, obj) takes more time than the call d.add(obj) because
the former has to move d[k..] to make room for the new object obj . Take this
fact into account when designing and developing a program that uses a Vector .
The capacity increases automatically
If adding an element to a Vector would cause the size to exceed the capac-
ity, the capacity is automatically increased, i.e. more memory is allocated so that
the Vector can contain more elements. The capacity is not increased by 1
because that would be far too inefficient, but is always doubled. Doubling the
capacity might seem like overkill, but, for purposes of efficiency, it is best.
In general, then, you do not have to worry about the capacity of a Vector
because the class takes care of it automatically. However, there may be some sit-
uations where space is at a premium and you want to be sure the capacity is as
close to the real size as possible. Class Vector provides methods that allow you
to change the capacity and to change how many elements are added when the
capacity has to be increased. We do not describe these methods because they are
not necessary in a first course on programming.
Changing and retrieving elements
To replace one element of a Vector with another, use procedure SetElement .
Given Vector d as in Fig. 5.3, execution of the call:
d.set(2, "purple");
changes d to contain the elements: 4 (as an Integer ), "red" , "purple" . The first
argument of a call to set can be any integer in the range 0..d.size()-1 ; the
Search WWH ::

Custom Search