Like an Array, but More Dynamic

Problem

You don’t want to worry about storage reallocation; you want a standard class to handle it for you.

Solution

Use a Vector. Or, in Java 2, an ArrayList.

Discussion

A Vector is just a standard class that encapsulates the functionality of an array but allows it to expand automatically. You can just keep on adding things to it, and each addition will behave the same. If you watch really closely you might notice a brief extra pause once in a while when adding objects, as Vector reallocates and copies. But you don’t have to think about it.

However, because Vector is a class and isn’t part of the syntax of Java, you can’t use Java’s array syntax; you must use methods to access the Vector data. There are methods to add objects, retrieve objects, find objects, and tell you how big the Vector is and how big it can become without having to reallocate. Like those of all the collection classes in java.util, Vector’s storing and retrieval methods are defined in terms of java.lang.Object. But since Object is the ancestor of every defined type, you can store objects of any type in a Vector (or any collection), and cast it when retrieving it. If you need to store a small number of built-ins (like int, float, etc.) into a collection containing other data, use the appropriate wrapper class (see the Introduction to Chapter 5). To store booleans, either use a java.util.BitSet (see the online documentation) or the Boolean wrapper class.

Table 7-1 shows some of the ...

Get Java Cookbook 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.