Java Reference
In-Depth Information
int namesMax = names.capacity(); // Get current capacity
If this statement follows the definition you have for
names
in the previous example, the variable
namesMax
has the value 10. The
capacity()
method is not available in the
ArrayList<>
class.
You can ensure that a vector or an array list has sufficient capacity for your needs by calling its
en-
sureCapacity()
method. For example:
names.ensureCapacity(150); // Set minimum capacity to 150
If the capacity of
names
is less than 150, it is increased to that value. If it's already 150 or greater, it is
unchanged by this statement. The argument you specify is of type
int
. There's no return value.
Changing the Size
When you first create a
Vector<>
object , it is empty. The space allocated is occupied after you've stored
references in it. The number of elements you have stored in a
Vector<>
is referred to as its
size
. The size
of a
Vector<>
clearly can't be greater than the capacity. As you have seen, you can obtain the size as a
value of type
int
by calling the
size()
method. You could use the
size()
method in conjunction with the
capacity()
method to calculate the number of free entries in a
Vector<>
object
transactions
with the
following statement:
int freeCount = names.capacity() - names.size();
Storing an object in a vector increases its size, but you can also change the size of a vector directly by
calling a method; this does not apply to an array list. Using the method
setSize()
, you can increase and
decrease the size. For example:
names.setSize(50); // Set size to 50
The size of the
names
vector is set to the argument value (of type
int
). If the
names
vector has fewer than
50 elements stored, the additional elements up to 50 are filled with
null
references. If it already contains
more than 50 objects, all object references in excess of 50 are discarded. The objects themselves may still
be available if other references to them exist.
Looking back to the situation I discussed earlier, you saw how the effects of incrementing the capacity by
doubling each time the current capacity was exceeded could waste memory. A
Vector<>
or an
ArrayList<>
object provides you with a direct way of dealing with this — the
trimToSize()
method. This changes the
capacity to match the current size. For example:
names.trimToSize(); // Set capacity to size
If the size of the
names
vector is 30 when this statement executes, then the capacity is set to 30. Of course,
you can still add more objects to the
Vector<>
object, and it grows to accommodate them by whatever in-
crement is in effect.
Storing Objects
The simplest way to store an object is to use the
add()
method, as you did in the last example. To store a
name in the
names
vector, you could write the following: