LECTURE NOTES 15 NOVEMBER 2004 ARRAYS Why? - manipulate a collection of values - avoid naming each element independently What? - *array*: collection of data values of the same type What? - declaring an array How? [] ; []; Example? int[] testScore; float temperature[]; What? - internal representation of an array How? - array itself is a reference data type (draw an array variable and its memory) - amount of memory allocated to store it varies with the number and type of values in it - must use reserved word new to allocate this memory What? - initializing an array How? = new [] Example? temperature = new float[7]; (draw a picture) What? - array is not considered an object What? - combine declaration and allocation Example? - float temperature = new float[7]; What? - refering to the collection How? - use the array identifier What? - *array element*: one of the individual values in an array - *indexed expression*: expression used to refer to an array element How? - zero-based indexing - biggest index is one less than the number of elements in the array [] - n can be any integer expression Example - biggest index in temperature is 6 - if temperature is supposed to represent the temperature of Sunday-Saturday, I would refer to Friday's temperature with the expression: temperature[5] Why? - want to iterate through an array, but don't know size in advance What? - determining the size of an array How? - public constant member length Example? temperature.length - would resolve to 7 What? - initializing an array (quickly) - force to do using a loop How? - instead of specifying the size of the array, just give a list of initial values - number of initial values determines the size [] = {, , ... , }; Example? - if this week's forecast is 34, 42, 44, 43, 45, 47, 33 float[] temperature = {34f, 42f, 44f, 43f, 45f, 47f, 33f}; Why? - array size is always the same - may not be most efficient use of space - if too small, must recompile the program - if too large, wasting memory What? - *fixed size array declaration*: size of the array is determined at compile time - *variable-size array declaration*: size of array is determined at run time How? - use a variable (or an expression including a variable) to specify the size STORING OBJECTS IN ARRAYS What? - declare an array of objects How? - use the name of a class instead of a primitive [] = new [[] = new (); Example? ourPets[0] = new Pet(); - the array element then points to an object - draw a picture What? - accessing members and methods of an object in an array How? - use indexed expression to refer to the object instead of a variable [].; Example? ourPets[0].setSpecies("cat");