Introduction to arrays Data in economy size packages Array • Data structure that contains a collection of data items – All items are of the same data type – Access to the entire collection via the array name – Access to individual elements via their indexes (or subscripts) • Behaves like a list of variables with a uniform naming mechanism Example • Suppose you needed to store 20 distinct whole-number values; what can you do? – Declare 20 distinct int variables, giving each a unique name – Declare a single int array with the capacity to hold 20 elements • Which is preferable? What if the problem involved 200 numbers? 2000? 2,000,000? Array declaration • The syntax for array declaration is: data type [ ] identifier; – “data type” is any built-in, library or userdefined data type (int, double, char, String, etc.) – “identifier” is a valid Java identifier – Java supports a variation of this syntax, which is closer to C/C++ syntax: data type identifier[ ]; Array creation • An array is a reference data type, similar to a class • Declaration doesn’t allocate any memory; this is done, as with objects, with the new operator • Examples: double [] averages = new double[10]; char [] alphabet; alphabet = new char[26] Array creation • The number in square brackets when an array is created indicates the number of elements that can be stored in the array • Any positive int expression can be used to allocate an array • Example: public static final int LETTERS = 26; char [] asciiAlphabet = new char [LETTERS * 2]; Array indexing & length • The length of the array is determined when it is created; the value is stored in a public instance variable, length • asciiAlphabet.length has the value 52 • If an array is created with size n, the subscripts of its elements are numbered (in order) from 0 to n-1 • So, for example, the first element in the asciiAlphabet array is element 0, and the last element is element 51 One overloaded operator • We have already seen two uses for the indexing operator ([]): – Array declaration; for example, int [] nums; – Array creation; nums = new int [20]; • This operator has one more use: access to individual array elements, or indexing Accessing individual array values • An element is accessed via its index or subscript • The notation for accessing an element via its subscript is: arrayName[subscript] where – “arrayName” is the array’s identifier – “subscript” is a number between 0 and size-1 • The first element has subscript 0, the second has subscript 1, the third has subscript 2, and so forth up to the last element, which has subscript length-1 Examples asciiAlpha[0] = ‘A’; System.out.print(“” + asciiAlpha[8]); averages[7] *= 0.5; • Note: although these examples use literal values, a subscript can be any int expression • It is up to the programmer to ensure that the subscript value is within the bounds of the array Filling an array with initial values char [] upperAlpha = new char [26]; for (char c = ‘A’; c <= ‘Z’; c++) upperAlpha[(int)(c – ‘A’)] = c; Trace: c ‘A’ ‘B’ ‘C’ ... ‘Z’ ‘[‘ c – ‘A’ 0 1 2 25 26 value stored ‘A’ ‘B’ ‘C’ ‘Z’ Initializing at declaration List all values in a block of code, terminating with a semicolon: char [] lowerAlpha = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’}; Compiler automatically sizes array to hold the specified data; array will remain this size, even if different data assigned: for (int x = 0; x < 10; x++) lowerAlpha[x]=‘!’ What values are assigned? float [] temps = float[ 5 ] ; // allocates memory for array int m ; for (m = 0; m < 5; m++) { temps[ m ] = 100.0 + m * 0.2 ; } 7000 7004 7008 7012 7016 ? ? ? ? ? temps[0] temps[1] temps[2] temps[3] temps[4] 13 Now what values are printed? float [] temps = float[ 5 ] ; // allocates memory for array int m ; ..... for (m = 4; m >= 0; m-- ) { System.out.println(“” + temps[ m ]) ; } 7000 100.0 temps[0] 7004 7008 7012 7016 100.2 100.4 100.6 100.8 temps[1] temps[2] temps[3] temps[4] 14 Variable Subscripts float [] temps = new float[ 5 ] ;//allocates memory for array int m = 3 ; ...... What is temps[ m + 1] ? What is temps[ m ] + 1 ? 7000 100.0 temps[0] 7004 7008 7012 7016 100.2 100.4 100.6 100.8 temps[1] temps[2] temps[3] temps[4] 15 Arrays of objects • Arrays can be collections of elements of any data type, including classes • For example, suppose we wanted to create an array of Fraction objects: – Array declaration: Fraction [] ratios = new Fraction[100]; – This creates the array, but not the individual Fraction objects it will contain; these have to be created individually, as shown on the next slide Initializing an array of objects for (int x = 0; x < ratios.length; x++) ratios[x] = new Fraction(); // initializes entire array with values 1/1 Random rg = new Random(); for (int y = 0; y < ratios.length; y++) ratios[y] = new Fraction (rg.nextInt(10) +1, rg.nextInt(20) + 1); // initializes array with random values Methods & array parameters • An array element can be passed to any method that takes its base type as an argument • For example, in the Fraction class the plus method takes a Fraction argument; elements of the array declared on the previous slide could serve as both calling object and argument: ratios[0] = ratios[1].plus(ratios[2]) Methods & array parameters • An entire array can be passed as an argument to a method, if such a parameter is specified – example: public static void fillFractionArray (Fraction [] fracs) { Random rg = new Random(); for (int x = 0 ; x < fracs.length; x++) fracs[x] = new Fraction (rg.nextInt(10)+1,rg.nextInt(20)+1); • A call to this method: Fraction [] ratios = new Fraction[25]; Fraction.fillFractionArray(ratios); • Note that the square brackets are not used when an entire array is passed as an argument public static void main (String [] args) { What is args? A. B. C. D. A String An array of Strings Nothing None of the above