next up previous index
Next: Stacks Up: Arrays Previous: Multi-Dimensional Arrays   Index


Array Access and Memory Allocation

One of the principal reasons arrays are used so widely is that their elements can be accessed in constant time. This means that the time taken to access a[i] is the same for each index i. This is because the address of a[i] can be determined arithmetically by adding a suitable offset to the address of the head of the array. The reason is that space for the contents of an array is allocated as a contiguous block of memory.

This feature, however, is also one of the limitations of arrays. Once the space is allocated, it cannot be extended. There is no guarantee that the next block of memory will be free at some time later in the execution of the program. In this sense arrays are static data structures.

On the other hand, arrays can be allocated dynamically in Java. This contrasts with a number of programming languages in which all array sizes must be known at compile time. This is not true of Java. The following, for example, is valid:

int n = 20;
int a[] = new int[n];
Although n was initialised here at declaration, it could equally have been set in any way during program execution, e.g. as a consequence of file or keyboard input. It is still true, however, that once space has been allocated, it cannot be extended.

In order to overcome this limitation, Java provides a Vector class in the java.util package which effectively provides arrays that can grow or shrink dynamically. In reality, however, once the array is full, another larger array is created and the contents of the first are copied into the second; but this is opaque to the user. We shall need a facility like this when dealing with stacks and queues. But it will be clearer to write the simple code necessary explicitly when it is needed.


next up previous index
Next: Stacks Up: Arrays Previous: Multi-Dimensional Arrays   Index
Peter Williams 2005-06-07