Java Arrays of Objects

ArrayList and LinkedList are list classes in the Java library. They both take care of allowing the list to grow to any size, and they provide numerous methods to manipulate lists. Usually, you'll use these classes to store lists of things.

Most languages, including Java and C#, also provide the 'array', which is a built-in construct of the language. We discussed arrays briefly before:

Here are the basics:


int[] arr;  // declares a variable arr with a type of int array.


arr = new int[5];  // create an array of 5 integers.

All at Once

int[] arr = new int[5];


arr[2]= 4;
int x = arr[4];

Arrays of Objects

Arrays which have elements that are objects are somewhat tricky. The programmer must create both the array, and each element. This is due to the fact that each element of the array is a reference to a Person, not the Person itself.

Person[] personArray;  // declares a variable 'personArray' of type Person array.

personArray = new Person[7];  // creates slots to hold seven persons. No Person is created yet.

for (int i=0;i<7;i++)
    personArray[i]= new Person();  // create each actual Person


1. What would occur if the for loop above was not there?

2. Suppose the code above were in a main function, and the class Person had name and age data members. Trace the code.