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

Arrays of Objects

So far we have only considered arrays of elements of the various primitive types. All elements of such an array must be of the same type. But we can also have arrays of objects of any class. For example
String[] words = new String[20];
creates a String array with 20 elements. More generally we can have Object arrays. Thus
Object[] heap = new Object[20]
declares heap to be an array of 20 Objects.

It is important to remember that arrays must be initialised if they are to hold data that is different from the default initialisation. For arrays of Objects, the default initialisation is the null reference. Thus, with the declaration of words, we have not created any strings. Elements of the words array must be initialised, for example, by

words[0] = new String("");
which assigns to the array element words[0] a reference to the empty string.

An alternative way of initialising string arrays is by an initialiser list, for example

String[] words = {"the", "cat", "sat", "on", "the", "mat"};
which initialises words to be an array of length six containing the specified strings.



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