In order to use vectors you need the following import:
Vectors are created using the standard object syntax:
Vector v = new Vector();
To add an element to a vector:
(the string is added at the end of the vector)
String s = new String("Hi there!"); v.add(s)
You may add an element at any index:
works like "insertAt" for StringBuffer, i.e. the elements
after that index are shifted to the right.
One thing is very important for understanding vectors: vectors store objects, not data of primitive types (you can still use them for integers, etc., see below). When you access an element of a vector, it is stored as an Object, so you need to typecast it before you can do anything useful with it. For instance, if the vector stores strings:
Note that this doesn't remove the element from the vector. To remove the element, do this:
String s = v.elementAt(0); // doesn't work!!! String s = (String) v.elementAt(0); // works
You can access an element and remove it at the same time:
See the Vector API for more methods.
String s = (String) v.remove(0);
Note that generally vectors are slower than arrays, so you should use them only when you don't have a good estimate of the size of data.
The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.