800 likes | 817 Views
Java Programming: From Problem Analysis to Program Design, 3e Chapter 9. Arrays. Chapter Objectives. Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of “array index out of bounds” Become familiar with the restrictions on array processing.
E N D
Java Programming: From Problem Analysis to Program Design, 3eChapter 9 Arrays
Chapter Objectives • Learn about arrays • Explore how to declare and manipulate data into arrays • Understand the meaning of “array index out of bounds” • Become familiar with the restrictions on array processing
Chapter Objectives (continued) • Discover how to pass an array as a parameter to a method • Discover how to manipulate data in a two-dimensional array • Learn about multidimensional arrays
Array • Definition: structured data type with a fixed number of elements • Elements of an array are also called components of the array • Every element is of the same type • Elements are accessed using their relative positions in the array
One-Dimensional Arrays (continued) • intExp = number of components in array >= 0 • 0 <= indexExp <= intExp
Arrays Array num:int[] num = new int[5];
Array Initialization During Declaration • The initializer list containsvalues, called initial values, that are placed between braces and separated by commas • Here, sales[0]= 12.25, sales[1]= 32.50, sales[2]= 16.90, sales[3]= 23.00, and sales[4]= 45.68
Using Initializer Lists • When declaring and initializing arrays, the size of the array is determined by the number of initial values within the braces • If an array is declared and initialized simultaneously, we do not use the operator new to instantiate the array object
Arrays and the Instance Variable length • Associated with each array that has been instantiated, there is a public (final) instance variable length • The variable length contains the size of the array • Do NOT confuse this with the length() method used in strings. With arrays, length is a field. • The variable length can be directly accessed in a program using the array name and the dot operator
Arrays and the Instance Variable length (continued) int[] list = {10, 20, 30, 40, 50, 60}; • This statement creates the array list of six components and initializes the components using the values given • list.length is 6 int[] numList = new int[10]; • This statement creates the array numList of 10 components and initializes each component to 0
Arrays and the Instance Variable length (continued) • The value of numList.length is 10 numList[0] = 5; numList[1] = 10; numList[2] = 15; numList[3] = 20; • These statements store 5, 10, 15, and 20, respectively, in the first four components of numList • You can store the number of filled elements, that is, the actual number of elements, in the array in a variable, say numOfElement • When dealing with an array that is only partially filled, it is good programming practice for your program to keep track of the number of filled elements in an array (i.e. use a variable)
Repeat: Keeping Track of Length • Again: So far we’ve dealt only with arrays that we assume are filled with valid data. However it’s important to recognize that we will often (perhaps mostly) be dealing with arrays that are only partially filled with meaningful information. In these situations, we must have a variable that keeps track of how much of our array is “relevant”. • This way, when we loop, we will NOT loop from i=0 until i < array.length. • Instead we will loop from i=0 until i < variable_keeping_track_of_array
Processing One-Dimensional Arrays • Loops used to step through elements in array and perform operations int[] list = new int[100]; int i; for (i = 0; i < list.length; i++) //process list[i], the (i + 1)th //element of list for (i = 0; i < list.length; i++) list[i] = console.nextInt(); for (i = 0; i < list.length; i++) System.out.print(list[i] + " ");
Arrays (continued) • Some operations on arrays: • Initialize (e.g. set all values to -1) • Input data (e.g. from a file, from the user) • Output stored data • Find largest/smallest/sum/average of elements • Etc… double[] arrSales = newdouble[10]; int index; double largestSale, sum, average;
Code to Initialize Array to Specific Value (10.00) for (index = 0; index < arrSales.length; index++) arrSales[index] = 10.00;
Code to Read Data into Array for (index = 0; index < arrSales.length; index++) arrSales[index] = console.nextDouble();
Code to Print Array for (index = 0; index < arrSales.length; index++) System.out.print(arrSales[index] + " ");
Code to Find Sum and Average of Array sum = 0; for (index = 0; index < arrSales.length; index++) sum = sum + arrSales[index]; if (arrSales.length != 0) average = sum / arrSales.length; else average = 0.0;
Determining Largest Element in Array maxIndex = 0; for (index = 1; index < arrSales.length; index++) if (arrSales[maxIndex] < arrSales[index]) maxIndex = index; //Note: no need for braces here largestSale = arrSales[maxIndex];
Array Index Out of Bounds • Array in bounds if: 0 <= index <= arraySize – 1 • If index < 0 or index > arraySize: ArrayIndexOutOfBoundsExceptionexception is thrown We will discuss exceptions in a later lecture • Base address: memory location of first component in array
The Assignment Operators and Arrays Supposing I were to write: listB = listA; ?
Relational Operators Arrays • if (listA == listB) Will this work? • - The expression listA == listB determines if the values of listA and listB are the same and thus determines whether listA and listBrefer (point) to the same array • - To determine whether listA and listB contain the same elements, you need to compare them element by element • - You can write a method that returns true if two int arrays contain the same elements
* Relational Operators and Arrays (continued) boolean isEqualArrays(int[] firstArray, int[] secondArray) { if (firstArray.length != secondArray.length) return false; //could save us time! for (int index = 0; index < firstArray.length; index++) if (firstArray[index] != secondArray[index]) return false; return true; } if (isEqualArrays(listA, listB)) ...
* Arrays as Parameters to Methods //Why the extra parameter to this method? In this second method, we don’t use the field ‘length’. You would want to do this in a situation where you have an array that is not completely filled. (e.g. only 10 elements of an array of size 20 has meaningful values)
* Arrays of Objects (important) • Can use arrays to manipulate objects • Example: create array named records with 20 objects of type StudentRecord: StudentRecord[] records = new StudentRecord[20] • Can fill records with instances of StudentRecord objects as follows: for(int j=0; j <records.length; j++) records[j] = new StudentRecord();
Array of String Objects String[] nameList = new String[5]; nameList[0] = "Amanda Green"; nameList[1] = "Vijay Arora"; nameList[2] = "Sheila Mann"; nameList[3] = "Rohit Sharma"; nameList[4] = "Mandy Johnson";
* Do not confuse the array as a whole with individual elements • Consider the nameList[] array from the previous slide. If I were to ask you the data-type of nameList, many of you would be tempted to say ‘String’ or ‘array’. Yet neither is correct. The correct answer is “an array of String objects’ • If I were to ask you the data type of nameList[0] however, it is vitally important that you recognize that the answer is String. For example • How might you check to see if the first element of the array is “Robert”? if ( nameList[0].equals(“Robert”) ) { ... • How might you check to see if the first two elements of the array are identical? if ( nameList[0].equals( nameList[1] ) ) { ... • How might you check the length of the last element of the array? if ( nameList[namelist.length -1].length() ) { ...
Arrays of Objects contd Your book gives an example class called ‘Clock’ that has fields to represent hours, minutes and seconds: public class Clock { private int hr; //store hours private int min; //store minutes private int sec; //store seconds etc.... Suppose you had 100 employees who are paid on an hourly basis and you want to keep track of their arrival and departure times. You could create an array of 100 Clock objects to represent their arrival times, and also have an additional array of 100 Clock objects to represent their departure times.
Arrays of Objects (continued) Clock[] arrivalTimeEmp = new Clock[100];
Instantiating Array Objects for (int j = 0; j < arrivalTimeEmp.length; j++) arrivalTimeEmp[j] = new Clock();
Instantiating Array Objects (continued) arrivalTimeEmp[49].setTime(8, 5, 10);
Array of objects continued • You could output all of the information for each employee in the usual way: • for (int i=0; i<arrivalTimeEmp.length; i++) • System.out.print( arrivalTimeEmp[i] ); • … as long as????? The toString() method has been written (overridden) for the class
We will skip this section for 212. This is for your interest only at this point. Skip to the slide on the ‘foreach’ loop Arrays and Variable Length Parameter List • The syntax to declare a variable length formal parameter (list) is: dataType ... identifier