Java Reference
In-Depth Information
If the default capacity isn't suitable for what you want to do, you can set the initial capacity of a Vector
explicitly when you create it by using a different constructor. You just specify the capacity you require
as an argument of type int . For example:
Vector transactions = new Vector(100); // Vector to store 100 objects
The Vector object we're defining here will store 100 elements initially. It will also double in capacity
each time you exceed the current capacity. The process of doubling the capacity of the Vector when
more space is required can be quite inefficient. For example, if you end up storing 7000 objects in the
Vector we've just defined, it will actually have space for 12800 objects. If each object reference
requires 4 bytes, say, you'll be occupying more than 20 kilobytes of memory unnecessarily.
One way of avoiding this is to specify the amount by which the Vector should be incremented as well
as the initial capacity when you create the Vector object. Both of these arguments to the constructor
are of type int . For example:
Vector transactions = new Vector(100,10);
This Vector object has an initial capacity of 100, but the capacity will only be increased by 10
elements each time more space is required.
Why don't we increment the Vector object by 1 each time then? The reason is that the process of
incrementing the capacity takes time because it involves copying the contents to a new area of
memory. The bigger the vector is, the longer the copy takes, and that will affect your program's
performance if it happens very often.
The last constructor creates a Vector object containing object references from another collection that is
passed to the constructor as an argument of type Collection . Since all the set and list collection
classes implement the Collection interface, the constructor argument can be of any set or list class
type, including another Vector . The objects are stored in the Vector object that is created in the
sequence in which they are returned from the iterator for the Collection object that is passed as the
argument.
Let's see a vector working.
Try It Out - Using a Vector
We'll take a very simple example here, just storing a few strings in a vector:
import java.util.*;
public class TrySimpleVector {
public static void main(String[] args) {
Vector names = new Vector();
String[] firstnames = { "Jack", "Jill", "John",
"Joan", "Jeremiah", "Josephine"};
for(int i = 0 ; i<firstnames.length ; i++)
names.add(firstnames[i]);
Search WWH ::




Custom Search