Question

How do I use the Vector class, from the java.util package?

Answer

Using the Vector class, rather than creating your own linked-list structure is a good idea. Vectors are extremely easy to use, and implement the Enumeration interface which makes traversing the contents of a Vector extremely easy.

Creating a vector is easy. Simply define a variable of type Vector, and call the vector constructor.

// Create an instance of class Vector ....
Vector myVector = new Vector ();

// ... or suggest an initial vector size
myVector = new Vector(50);

Vector instances, like linked-lists, can grow dynamically. Once the vector reaches its maximum limit, it dynamically allocated resources and increases its maximum. However, if you know you're going to insert a large amount of data, you may want to specify an initial estimate.

Vector instances can store any type of object - you simply insert an object via the addElement method.

for (int i = 1; i <= 20; i++)
{
	myVector.addElement( new String ("I am string " + i));
}

When you wish to access the elements of the vector, you can look at individual elements (via their offset within the vector which is in ascending order), or you can traverse the entire list.

// Peek at element 5
System.out.println ("Element : " + myVector.elementAt(5) );

Traversing the entire vector is a common opperation. Remember, however, that when you insert an object via the addElement, it is implicitly cast to an instance of Object. Object is the base class of all other Java classes, and you'll need to explicitly cast it to another object type.

// Traverse entire list, printing them all out
for (Enumeration e = myVector.elements(); e.hasMoreElements();)
{
	String myString = (String) e.nextElement();
	System.out.println(myString);
}

Traversing a list is made extremely simple through the use of the Enumeration interface. Enumerations are great, because they allow you to easily process all elements, without having to determine the length of the vector, and manually accessing each element. Instead, it returns all the elements through the nextElement method.

Vectors provide an easy interface, and have the advantage that they can grow dynamically, whereas arrays are of fixed length. Consider using them in your next Java project!


Back