14.5. Using Vectors

The Vector<T> parameterized type defines a sequence collection of elements of any type T. A Vector<> object works rather like an array, but with the additional feature that it can grow itself automatically when you need more capacity. The Vector<> type implements the List<> interface, so you can also access the contents of containers of this type as a list.


Like arrays, vectors hold object references only, not actual objects. To keep the text simple I'll refer to a Vector<> as holding objects, and I'll make the distinction only when it's important. However, you should keep in mind that all the collection classes you're about to encounter hold object references.

14.5.1. Creating a Vector

You have four constructors for a Vector<>. The default constructor creates an empty Vector<> object with the capacity to store up to a default number of objects of the type argument that you supply. The default capacity of a Vector<> object is ten objects, and the Vector<> object will double in size when you add an object when it is full. For example:

Vector<String> transactions = new Vector<String>();

This statement creates an empty vector with a capacity for ten String objects. If the default capacity isn't suitable for what you want to do, you can set the initial capacity of the Vector<> object explicitly when you create it by using a different constructor. You just specify the capacity you require as an argument of type int. For example:

Vector<String> transactions ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 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.