Collections - Vectors vs Arrays

Table of Contents

Vectors vs Arrays

In many cases, a vector and an array may be used interchangeably. Generally, though, one is preferred over the other for any given circumstance. As a good general rule of thumb, we would use an array anytime the collection meets the following conditions:

  1. All elements of the collection are of the same type (especially the primitive types).
  2. The collection is a known, fixed size or maximum size.
  3. The collection is a non-sorted data set (data is not inserted into the collection).

If any of these conditions are not met, it might be better to use a vector object. Generally, the choice is pretty clear. If it necessary to manipulate the storage of the data, regardless of whether the data itself is manipulated, it probably is better to use a vector instead of an array. The advantages of the vector are mainly the fact that the collection is of a dynamic size and that methods are available to manipulate the storage.

If we want to perform an insert into an array, assuming that we have space for the additional member, we would have to do something along these lines:

System.arrayCopy( myArray, insertPosition, myArray, insertPosition + 1, array.length - insertPosition );
myArray[insertPosition] = newElement;

This is basically what the vector’s insertElementAt() method does.

The advantages of using an array are speed, easy access, and reduced overhead. As mentioned earlier, the vector’s capability to expand as necessary comes with the price of creating and copying the collection to the new internal array. By allocating all the memory needed for the array at one time, these time-consuming operations are eliminated. Each access to an element in a vector also requires a method call, which is avoided by the simple index notation an array uses for element access.

The advantages of a vector are flexibility and control. The methods available in the vector enable the programmer to manipulate the collection at will. It is a simple matter to insert or move an element in the collection.


Links to this note