A Vector is like an array except that it can dynamically grow or shrink.
To use a Vector, you must import the Vector class:
import java.util.Vector;
Vector people = new Vector(); // create empty vector
people.addElement(new String("Sam")); // add a String object
people.addElement("Sally"); // add another String object
System.out.println(people.firstElement());
System.out.println(people.elementAt(1));
System.out.println(people);
people.removeElement(0); // remove "Sam"
System.out.println(people);
Output will look like:
Sam
Sally
[Sam,Sally]
[Sally]
Unlike an array, a Vector can contain only objects - primitive types are not allowed.
Vector numbers = new Vector(); // create empty vector
numbers.addElement(45); ILLEGAL
numbers.addElement(new Integer(45)); // ok
Unlike an array, a Vector can contain a mixture of different types of objects. Strictly speaking, a Vector contains only objects of type Object. However, all Java objects are derived from the Object Class.
Vector person = new Vector();
String name = "Janis"; // create a String object
person.addElement(name); // add String object to Vector
Integer age = new Integer(12); // create an Integer object
person.addElement(age); // add Integer to Vector
Vectors are more flexible but also more awkward to use than arrays.
For example, since the type of each item is formally Object, explicit casts must be used to tell compiler the actual type of object that is stored.
// Retrieve the first String from a vector and send
// message to that String to find the length:
int len = ( (String) people.elementAt(0) ).length();
Using Vectors to store numbers is annoying. For example, if you want to retrieve an integer stored in your Vector:
int n = ( (Integer) person.elementAt(1)).intValue();
See API reference for other methods for Vectors.
Using a Vector to store a list of employees is better than an array because Vectors can change size as the number of employees changes.