Java Reference
In-Depth Information
these methods is the contains() method, which simply checks whether an element is in
the vector:
boolean isThere = v.contains(“Webb”);
8
Another method that works in this manner is the indexOf() method, which finds the
index of an element based on the element itself:
int i = v.indexOf(“Inkster”);
The indexOf() method returns the index of the element in question if it is in the vector,
or -1 if not. The removeElement() method works similarly, removing an element based
on the element itself rather than on an index:
v.removeElement(“Kung”);
The Vector class offers a few methods for determining and manipulating a vector's size.
First, the size method determines the number of elements in the vector:
int size = v.size();
If you want to explicitly set the size of the vector, you can use the setSize() method:
v.setSize(10);
The setSize() method expands or truncates the vector to the size specified. If the vector
is expanded, null elements are inserted as the newly added elements. If the vector is
truncated, any elements at indexes beyond the specified size are discarded.
Recall that vectors have two different attributes relating to size: size and capacity. The
size is the number of elements in the vector, and the capacity is the amount of memory
allocated to hold all the elements. The capacity is always greater than or equal to the
size. You can force the capacity to exactly match the size by using the trimToSize()
method:
v.trimToSize();
You also can check to see what the capacity is by using the capacity() method:
int capacity = v.capacity();
Looping Through Data Structures
If you're interested in working sequentially with all the elements in a vector, you can use
the iterator() method, which returns a list of the elements you can iterate through:
Iterator it = v.iterator();
Search WWH ::




Custom Search