Java Reference
In-Depth Information
The following code shows how to create a vector with a specified capacity:
Vector v = new Vector(25);
This vector allocates enough memory to support 25 elements. After 25 elements have
been added, however, the vector must decide how to expand to accept more elements.
You can specify the value by which a vector grows using another Vector constructor:
8
Vector v = new Vector(25, 5);
This vector has an initial size of 25 elements and expands in increments of 5 elements
when more than 25 elements are added to it. That means that the vector jumps to 30 ele-
ments in size, and then 35, and so on. A smaller growth value results in greater memory
management efficiency, but at the cost of more execution overhead, because more mem-
ory allocations are taking place. A larger growth value results in fewer memory alloca-
tions, although memory might be wasted if you don't use all the extra space created.
You can't just use square brackets (“[ ]”) to access the elements in a vector, as you can in
an array. You must use methods defined in the Vector class.
Use the add() method to add an element to a vector, as in the following example:
v.add(“Pak”);
v.add(“Han”);
v.add(“Inkster”);
This code shows how to add some strings to a vector. To retrieve the last string added to
the vector, you can use the lastElement() method:
String s = (String)v.lastElement();
Notice that you have to cast the return value of lastElement() because the Vector class
is designed to work with the Object class.
The get() method enables you to retrieve a vector element using an index, as shown in
the following code:
String s1 = (String)v.get(0);
String s2 = (String)v.get(2);
Because vectors are zero-based, the first call to get() retrieves the “Pak” string, and the
second call retrieves the “Han” string. Just as you can retrieve an element at a particular
index, you also can add and remove elements at an index by using the add() and
remove() methods:
v.add(1, “Park”);
v.add(0, “Sorenstam”);
v.remove(3);
Search WWH ::




Custom Search