Java Reference
In-Depth Information
If this statement follows the current definition we have for transactions , the variable transMax will
have the value 100.
You can also ensure that a Vector has a sufficient capacity for your needs by calling its
ensureCapacity() method. For example:
transactions.ensureCapacity(150); // Set minimum capacity to 150
If the capacity of transactions is less than 150, the capacity will be increased to that value. If it's
already 150 or greater, it will be unchanged by this statement. The argument you specify for
ensureCapacity() is of type int . There's no return value.
Changing the Size
When you first create a Vector object, the elements don't reference anything. An element will be
occupied once you've stored an object in it. The number of elements that are occupied by objects in a
Vector is referred to as the size of the Vector . The size of a Vector clearly can't be greater than the
capacity. As we have seen, you can obtain the size of a Vector object as a value of type int by calling
the size() method for the object. For example, you could calculate the number of free entries in the
Vector object transactions with the statement:
int freeCount = transactions.capacity() - transactions.size();
You usually increase the size value for a Vector indirectly by storing an object in it, but you can also
change the size directly by calling a method. Using the method setSize() , you can increase and
decrease the size. For example:
transactions.setSize(50); // Set size to 50
The size of the Vector is set to the argument value (of type int ). If the Vector transactions has
less than fifty elements occupied, the additional elements up to fifty will be filled with null references.
If it already contains more than fifty objects, all object references in excess of fifty will be discarded.
The objects themselves may still be available if other references to them exist.
Looking back to the situation we discussed earlier, we saw how the effects of incrementing the capacity
by doubling each time the current capacity was exceeded could waste memory. A Vector object
provides you with a direct way of dealing with this - the trimToSize() method. This just changes the
capacity to match the current size. For example:
transactions.trimToSize(); // Set capacity to size
If the size of the Vector is 50 when this statement executes, then the capacity will be too. Of course,
you can still add more objects to the Vector as it will grow to accommodate them.
Search WWH ::




Custom Search