Arrays
Arrays When a value is to be used in a program, a variable is declared to hold that value What about storing the results of exams for a large class…200 results = 200 variable declarations? Solution is to use Arrays… An array is a structure that holds multiple values of the same type. The length of an array is established when the array is created (at runtime). After creation, an array is a fixed-length structure.
Arrays are Objects and must be declared as such (use the new key word) int arrayExample[] = new int[10]; Creates an array of 10 Integers (all elements are of the same datatype e.g. int, float, Student etc.) Two parts to declaration… int arrayExample[] tells compiler there will be an array of integers referenced by the name arrayExample new int[10]assigns the size of the Array (sets it aside in memory – space for 10 integers needed) Arrays
Where confusion can arise… Arrays can be declared and initialised in either of the following ways… int[] arrayExample = new int[10]; int arrayExample[] = new int[10]; Both are correct and are down to preference, many different text books and programmers use both styles Declare & Create in one statement
Each place holder in an array is known as an element (we have 10 elements of type integer) Each element is uniquely identified by an index To refer to an element… arrayExample[index] NB Index values start at 0!!!!! Each element in an array has the same name as the array but a different value (index) in the square brackets Arrays
Creating an Array rainfall = new double[12]; This creates an array which can hold 12 elements. The first element will be stored at –rainfall[0] The last element will be stored at –rainfall[11] NOTE: the index of the first position in an array is 0.
If you try to reference an element using a higher index, this will result in an Exception (error) - ArrayIndexOutOfBoundsException When Arrays are first created the elements of the Arrays are initialised to 0 (false for Boolean and null for objects) Arrays
Dynamic Initialisation dataType nameOfArray[] = { }; There is no need for a ‘new’ statement, it will be done automatically Example int values[] = {4,2,7,1};
See Example 1
Arrays of Objects Arrays can hold objects in the same way they held fundamental data types Declaration for the array is the same: className arrayName[]; // Array creation step 1 arrayName = new className[3]; // Array step 2
Accessing objects in an array Use the array index as if it were an object variable arrayName[0].methodName();arrayName[1].variableName;
Example class Student { String name; String ID; int mark; public void setName (String n) {.....} public void setid (String Id) { } Student bis[] = new Student[3]; bis[0] = new Student(); bis[0].setName ("Paul"); bis[0].setId ("987654");
See Example 2