Java vectors (a brief intro)

Java vectors are similar to arrays in a sense that you can store data items in vectors and access them by index. The main difference is that vectors are extensible: they can grow and shrink as data items are added to them. This makes vectors more convenient to use in programs where the data size is unknown beforehand and changes throughout the program.

In order to use vectors you need the following import:

import java.util.*;

Vectors are created using the standard object syntax:

Vector v = new Vector();

To add an element to a vector:

String s = new String("Hi there!");
(the string is added at the end of the vector)

You may add an element at any index: v.add(1,s). This 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:

String s = v.elementAt(0); // doesn't work!!!
String s = (String) v.elementAt(0); // works
Note that this doesn't remove the element from the vector. To remove the element, do this:

You can access an element and remove it at the same time:

String s = (String) v.remove(0);
See the Vector API for more methods.

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.

This is a page from CSci 1211 course.

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.