Java Reference
In-Depth Information
for(int i = 0 ; i<names.size() ; i++)
System.out.println((String)names.get(i));
}
}
If you compile and run this, it will list the names that are defined in the program.
How It Works
We copy the references to the Vector object, names , in the first for loop. The add() method adds
the object to the vector at the next available position. The second for loop retrieves the String
references from the vector using the get() method. This returns the reference at the index position
specified by the argument as type Object , so we have to cast it to the original type, String , in the
println() call. The size() method returns the number of elements in the Vector , so this is the
upper limit for the second for loop. Note that the Vector object doesn't care what type of objects are
added - we could pass any type of reference to the add() method, even type Vector .
The Capacity and Size of a Vector
Although we said at the beginning that a Vector works like an array, this isn't strictly true. One
significant difference is in the information you can get about the storage space it provides. An array has
a single measure, its length, which is the count of the total number of elements it can reference. A vector
has two measures relating to the space it provides - the capacity and the size .
Vector v = newVector();
Capacity increases
automatically
Initial Capacity
Object
v.get(0)
Object
v.get(1)
Object
v.get(10)
Object
v.get(11)
Size is the number of
objects stored
Capacity is the maximum
number of objects that can
be stored
The capacity of a Vector is the maximum number of objects that it can hold at any given instant. Of course,
the capacity can vary over time, because when you store an object in a Vector object that is full, its capacity
will automatically increase. For example, the Vector object transactions that we defined in the last of
the constructor examples earlier had an initial capacity of 100. After you've stored 101 objects in it, its
capacity will be 110 objects. A vector will typically contain fewer objects than its capacity.
You can obtain the capacity of a Vector with the method capacity() , which returns it as a value of
type int . For example:
int transMax = transactions.capacity(); // Get current capacity
Search WWH ::




Custom Search