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: http://cs.usfca.edu/~wolber/courses/110/lectures/lists_in_java.htm

Here are the basics:

Declaration

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

Instantiation

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

All at Once

int[] arr = new int[5];

Set/Get

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
}

personArray[1].name="Joe";

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.