Vectors (the java.util.Vector class)
are commonly used instead of arrays, because they expand
automatically when new data is added to them.
The Java 2 Collections API introduced the similar ArrayList data structure.
ArrayLists are unsynchronized and therefore
faster than Vectors, but less secure in a multithreaded environment.
The Vector class was changed
in Java 2 to add the additional methods supported by ArrayList.
See below for a
reasons to use each. The description below is for the (new) Vector class.
Vectors can hold only Objects and not primitive types (eg, int).
If you want to put a primitive type in a Vector,
put it inside an object (eg, to save an integer value use the Integer class
or define your own class). If you use the Integer wrapper,
you will not be able to change the integer value, so it is sometimes useful
to define your own class.
You must import either import java.util.Vector;
or import java.util.*;.
Vectors are implemented with an array, and when that array is full and an additional element
is added, a new array must be allocated. Because
it takes time to create a bigger array and copy the
elements from the old array to the new array, it is a little faster
to create a Vector with a size that it will commonly be when full. Of course, if you knew the
final size, you could simply use an array. However, for non-critical sections of code
programmers typically don't specify an initial size.
Vector v = new Vector();
Vector v = new Vector(300);
v.add(s); // adds s to the end of the Vector v
You can use a for loop to get all the elements from a Vector,
but another very common way to go over all elements in a Vector is to
use a ListIterator. The advantage of an iterator is that it it can be used
with other data structures, so that i