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.