Week 10 lecture topics

Arrays in Java

Arrays are collections of objects and can be defined to contain objects of any sort. The main differences are :-

For instance, to define an array of int's the following steps are necessary.

Firstly, declare a variable capable of referencing an array :-

        int [] data;         //data will reference an array of ints
                             //but is currently null
Then, allocate an array object with a set size :-
        data = new int[100]; //data now references an array of 100 ints
Finally, the array can be used to store and retrieve int's :-
        data[0] = 5;   //notice, arrays start from zero
        data[2] = data[0] * 5;

Arrays can be defined to contain objects, e.g. :-

        Animal [] cages;        //cages is a reference to an array of animal
                                //objects, but currently null.
        cages = new Animal[50]; //this is NOT a call to the constructor, but
                                //allocates an array of 50 pointers to
                                //animal objects - all initially null
        cages[0] = new Lion("Fred");  //calls the Lion constructor to create
                                      //and initialize a Lion instance and
                                      //associate it with array element 0.
Notice the extra step involved when using arrays to hold animals. Notice also that an array of Animals can contain any sub-class of Animal.

Hence if we declare an array of Object instances like this :-

        Object [] list = new Object[100];
Then we can put into it any object type we choose, but they are fixed in size.
Ten Key Points
  1. Arrays are fixed length collections
  2. All arrays start with element 0
  3. Arrays can contain built-in types like char, int, double, boolean
  4. Arrays have to be created(and size fixed) with the allocator - new
  5. The length of an array is given by the length attribute
  6. Arrays of objects can be created
  7. Object arrays can contain objects of the same class or any sub class
  8. Arrays of objects initially have null entries
  9. The elements of an array can be accessed or changed at any time
  10. The parameter to main is an array of String objects