topics
play

Topics Declaring and Instantiating Arrays Accessing Array - PDF document

Topics Declaring and Instantiating Arrays Accessing Array Elements Writing Methods Chapter 8 Aggregate Array Operations Using Arrays in Classes Single-Dimensional Arrays Searching and Sorting Arrays Using Arrays


  1. Topics • Declaring and Instantiating Arrays • Accessing Array Elements • Writing Methods Chapter 8 • Aggregate Array Operations • Using Arrays in Classes Single-Dimensional Arrays • Searching and Sorting Arrays • Using Arrays as Counters http://www.csam.iit.edu/~oaldawud Declaring and Instantiating Arrays Arrays • An array is a sequence of variables of the • Arrays are objects, so creating an array requires two steps: same data type. 1. declaring the reference to the array • The data type can be any of Java's primitive 2. instantiating the array types ( int, short, byte, long, float, double, • To declare a reference to the array, use this syntax: boolean, char ) or a class. datatype [] arrayName; • Each variable in the array is an element. • To instantiate an array, use this syntax: • We use an index to specify the position of arrayName = new datatype[ size ]; each element in the array. where size is an expression that evaluates to an integer and specifies the number of • Arrays are useful for many applications, elements. including calculating statistics or representing the state of a game. http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud Examples Default Values for Elements Declaring arrays: • When an array is instantiated, the elements are double [] dailyTemps; // elements are doubles assigned default values according to the array data String [] cdTracks; // elements are Strings type. boolean [] answers; // elements are booleans Auto [] cars; // elements are Auto references Array data type Default value int [] cs101, bio201; // two integer arrays byte, short, int, long 0 Instantiating these arrays: float, double 0.0 dailyTemps = new double[365]; // 365 elements cdTracks = new String[15]; // 15 elements char space int numberOfQuestions = 30; boolean false answers = new boolean[numberOfQuestions]; cars = new Auto[3]; // 3 elements Any object reference null cs201 = new int[5]; // 5 elements (for example, a String ) bio101 = new int[4]; // 4 elements http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud 1

  2. Combining the Declaration and Assigning Initial Values to Arrays Instantiation of Arrays • Arrays can be instantiated by specifying a list of Syntax: initial values. datatype [] arrayName = new • Syntax: datatype[size]; datatype [] arrayName = { value0, value1, … }; where valueN is an expression evaluating to Examples: the data type of the array and is the value to assign to the element at index N. double [] dailyTemps = new double[365]; • Examples: String [] cdTracks = new String[15]; int nine = 9; int numberOfQuestions = 30; int [] oddNumbers = { 1, 3, 5, 7, nine, nine + 2, boolean [] answers 13, 15, 17, 19 }; = new boolean[numberOfQuestions]; Auto sportsCar = new Auto( "Ferrari", 0, 0.0 ); Auto [] cars = new Auto[3]; Auto [] cars = { sportsCar, new Auto( ), int [] cs101 = new int[5], bio201 = new new Auto("BMW", 100, 15.0 ) }; int[4]; http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud Common Error Accessing Array Elements Trap • To access an element of an array, use this syntax: • An initialization list can be given only when arrayName[ exp ] the array is declared. where exp is an expression that – Attempting to assign values to an array evaluates to an integer. using an initialization list after the array is • exp is the element's index -- its position instantiated will generate a compiler error. within the array. • The index of the first element in an array is 0. • The new keyword is not used when an array is instantiated using an initialization list. Also, • length is a read-only integer instance variable no size is specified for the array; the number that holds the number of elements in the array and is accessed using this syntax: of values in the initialization list determines the size of the array. arrayName.length http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud Common Error Accessing Array Elements Trap Element Syntax • Attempting to access an element of an array arrayName[0] Element 0 using an index less than 0 or greater than arrayName.length – 1 will generate an arrayName[i] Element i ArrayIndexOutOfBoundsException at run time. Last element arrayName[arrayName.length - 1] • Note that for an array, length – without parentheses – is an instance variable, whereas for Strings , length( ) – with parentheses – is a method. • Note also that the array's instance variable is • See Example 8.1 CellBills.java named length , rather than size . http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud 2

  3. cellBills Array Instantiating an Array of Objects When instantiated: After assigning • To instantiate an array with a class data type: values: 1. instantiate the array 2. instantiate the objects • Example: // instantiate array; all elements are null Auto [] cars= new Auto[3]; // instantiate objects and assign to elements Auto sportsCar= new Auto( "Miata", 100, 5.0 ); cars[0] = sportsCar; cars[1] = new Auto( ); // cars[2] is still null • See Example 8.2 AutoArray.java http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud Standard for Loop Header for Aggregate Array Operations Array Operations for ( int i = 0; i < arrayName.length; i++ ) • We can perform the same operations on arrays – initialization statement ( int i = 0 ) creates index as we do on a series of input values. i and sets it to the first element ( 0 ). – calculate the total value – loop condition ( i < arrayName.length ) – find the average value continues execution until the end of the array is reached. – find a minimum or maximum value, etc. – loop update ( i++ ) increments the index to the next element, so that we process each element in • To perform an operation on all elements in an order. array, we use a for loop to perform the • Inside the for loop, we reference the current element operation on each element in turn. as: arrayName[i] http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud Printing All Elements of an Array Reading Data Into an Array • Example: This code prints each element in an • Example: this code reads values from the user array named cellBills , one element per line into an array named cellBills, which has previously been instantiated: (assuming that cellBills has been instantiated): Scanner scan = new Scanner(System.in); for ( int i = 0; i < cellBills.length; i++ ) for (int i=0;i<cellBills.length; i++) { { System.out.println( cellBills[i] ); System.out.print("Enter bill >"); } cellBills[i] = scan.nextDouble( ); } • See Example 8.3 PrintingArrayElements.java • See Example 8.4 ReadingDataIntoAnArray.java http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud 3

  4. Summing the Elements of an Finding Maximum/Minimum Array Values • Example: this code calculates the total value of all • Example: this code finds the maximum value in an array named cellBills : elements in an array named cellBills , which has previously been instantiated: // make first element the current maximum double maxValue = cellBills[0]; double total = 0.0, avg=0.0; //init total // start for loop at element 1 for (int i=0;i<cellBills.length; i++) for (int i=1;i<cellBills.length; i++) { { total += cellBills[i]; if ( cellBills[i] > maxValue ) } maxValue = cellBills[i]; System.out.println( "The total is " + } total ); System.out.println( "The maximum is " avg = total / cellBills.length + • See Example 8.5 SummingArrayElements.java maxValue ); • See Example 8.6 MaxArrayValue.java http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud Copying Arrays Copying Array References • Suppose we want to copy the elements of an billsBackup = cellBills; array to another array. We could try this code: has this effect: double [] billsBackup = new double [6]; billsBackup = cellBills; // incorrect! • Although this code compiles, it is logically incorrect!We are copying the cellBills object reference to the billsBackup object reference. We are not copying the array data. • The result of this code is shown on the next slide. http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud Copying Array Values Copying Array Values • Example: this code copies the values of all elements in an array named cellBills to an array named billsBackup , both of which have previously been instantiated with the same length : for ( int i = 0; i < cellBills.length; i++ ) { billsBackup[i] = cellBills[i]; } • The effect of this for loop is shown on the next slide. • See Example 8.7 CopyingArrayElements.java http://www.csam.iit.edu/~oaldawud http://www.csam.iit.edu/~oaldawud 4

Recommend


More recommend