Name

Vector<E>

Synopsis

This class implements an ordered collection—essentially an array—of objects that can grow or shrink as necessary. In Java 1.2, Vector has been modified to implement the List interface. Unless the synchronized methods of the Vector class are actually needed, ArrayList is preferred in Java 1.2 and later. In Java 5.0 this class has been made generic. The type variable E represents the type of the elements of the vector.

Vector is useful when you need to keep track of a number of objects, but do not know in advance how many there will be. Use setElementAt( ) to set the object at a given index of a Vector. Use elementAt( ) to retrieve the object stored at a specified index. Call add( ) to append an object to the end of the Vector or to insert an object at any specified position. Use removeElementAt( ) to delete the element at a specified index or removeElement( ) to remove a specified object from the vector. size( ) returns the number of objects currently in the Vector. elements( ) returns an Enumeration that allows you to iterate through those objects. capacity( ) is not the same as size( ); it returns the maximum number of objects a Vector can hold before its internal storage must be resized. Vector automatically resizes its internal storage for you, but if you know in advance how many objects a Vector will contain, you can increase its efficiency by pre-allocating this many elements with ensureCapacity( ).

Figure 16-68. java.util.Vector<E>

public class ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.