Вы находитесь на странице: 1из 88
Multidimensional Arrays and the ArrayList Class Introduction 91 92 93 Declaring and Instantiating Multidimen- sional Arrays 9.1.1 Declaring Multidimensional Arrays 9.1.2 Instantiating Multidimensional Arrays 9.1.3 Combining the Declaration and Instantiation of Multidimen- sional Arrays 9.1.4 Assigning Initial Values to Multi- dimensional Arrays Accessing Multidimensional Array Elements Aggregate Two-Dimensional Array Operations 9.3.1 Processing All the Elements of a ‘Two-Dimensional Array Processing a Given Row of a ‘Two-Dimensional Array Processing a Given Column of a ‘Two-Dimensional Array Processing a Two-Dimensional Array One Row at a Time Processing a Two-Dimensional Array One Column at a Time Displaying Two-Dimensional Array Data as a Bar Chart 93.2 9.3.3 93.4 9.3.5 9.3.6 94 95, 9.6 97 98 99 ‘Two-Dimensional Arrays Passed to and Returned from Methods Programming Activity 1: Working with ‘Two-Dimensional Arrays Other Multidimensional Arrays The ArrayList Class 9.7.1 Declaring and Instantiating ArrayList Objects ‘Methods of the ArrayList Class Looping Through an ArrayList Using an Enhanced for Loop Using the ArrayList Class in a Program Programming Activity 2: Working with the ArrayList Class Chapter Summary 9.7.2 9.73 9.74 9.10 Exercises, Problems, and Projects 9.10.1 Multiple Choice Exercises 9.10.2 Reading and Understanding Code 9.10.3 Fill In the Code 9.10.4 Identifying Errors in Code 9.10.5 Debugging Area—Using Messages from the Java Compiler and Java JVM 9.10.6 Write a Short Program 9.10.7 Programming Projects 9.10.8 Technical Writing 9.10.9 Group Project CHAPTER Multidimensional Arrays and the ArrayList Class Introduction In Chapter 8, we learned that arrays could be useful when we have a lot of data to store in memory. If we write a program to perform statistics on last year’s temperatures, it is convenient to set up an array of doubles of size 365 to store the daily temperature data. But what if in addition to analyzing daily temperatures, we want to analyze temperatures by the week, or by a particular day of the week? For instance, if we sail on weekends, we could want to know how many times the tem- perature was above 65 degrees on Saturdays and Sundays. If we are consid- ering investing in air conditioning at home, we might be interested in knowing how many weeks had temperatures above 90 degrees. If we are avid skiers, we could be interested in the number of weeks with tempera~ tures lower than 32 degrees. In this situation, we would want to organize our data along two dimen- sions: weeks and days of the week. If we were to visualize the data asa table, we could imagine a table made up of 52 rows, each row representing a week. Each row would have seven columns, representing the days of the week. This table is shown in Figure 9.1. Or we could imagine a table of, seven rows, each row representing a day of the week, and 52 columns, each column representing a week of the year. In either case, we can represent the Figure9.1 rows and columns of our temperature table using a two-dimensional array. Temperature Dataforthe More generally, multidimensional arrays allow us to represent data organ- Previous 52 Weeks ized along n dimensions with a single array. Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Week [35 28.6 | 29.3 38 43.1 45.6 | 49 Week2 [51.9 | 37.9 34.1 37.1 39 405 | 43.2 Weeks! [562 [519 [453 [48.7 42.9 35.5 | 38.2 Week 52 [33.2 [27.1 24.9 [29.8 32.7 39.9 [38.8 9.1. Declaring and instantiating Multidimensional Arrays E ind Instantiating Multidimensional Arrays Just like single-dimensional arrays, multidimensional arrays are imple- mented as objects, so creating a multidimensional array takes the same two steps as creating a single-dimensional array: LETT 1. declaring the object reference for the array 2. instantiating the array In arrays with elements of primitive types, each element of the array con- tains a value of that type. For example, in an array of doubles, each element contains a double value. In arrays with a class data type, each element is an object reference, which points to the location of an object of that class. 9.1.1 Declaring Multidimensional Arrays To declare a multidimensional array, we use the same syntax as for a single- dimensional array, except that we include an empty set of brackets for each dimension. Here is the syntax for declaring a two-dimensional array: datatype [ J[ ] arraytanes Here is the syntax for declaring a three-dimensional array: datatype CE ]L] arraynane; In order to keep things simple, we will concentrate on two-dimensional arrays at this point. We will discuss three- and four-dimensional arrays later in the chapter. The following statement declares an array to hold the daily high tempera- tures for the last 52 weeks: double [J] dailyTenps: ‘The brackets can be placed before or after the array name. So the following syntax for declaring a two-dimensional array is also valid: datatype arraynane [Jf Js We prefer to put the brackets right after the data type, because it’s easier to read. To store quiz grades for students, we could declare a two-dimensional array, where each row will store the quiz grades for a particular student and each column will store the grades for a particular quit char [1[] quizzes; // each element 1s a char The syntax is the same whether we declare arrays with basic data types or class types. 500 570 qi COMMON ERROR ‘TRAP Specifying the sizeof any ofthe dimensions ofa mul- tidimensional array inthe declaration will generate a compiler eor. CHAPTER 9 Multidimensional Arrays and the Arraylst Class Imagine that we are interested in keeping track of a fleet of cars within a multinational corporation. The corporation operates in various countries, and in each of these countries, some employees have a company car. For this situation, we can declare a two-dimensional array where the first dimension will represent the country and the second dimension will repre- sent the employee. Using our Auto class from Chapter 7, the following statement declares this two-dimensional array to hold Auto objects: Auto [J] carss You can also declare multiple multidimensional arrays of the same data type in one statement by inserting a comma after each array name, using this syntax: datatype [ J[ ] arrayNamel, arrayName2; Forexample, the following statement will declare two integer arrays to hold the number of stolen bases for two baseball players for each game in their career: int [[] brian, jons The first dimension represents the games (per season), and the second dimension represents the season. Notice that when we declare a multidimensional array, we do not specify how many elements the array will have. Declaring a multidimensional array does not allocate memory for the array; this is done in step 2, when we instantiate the array. For example, this code from the file Test.java: double [7] [52] dailyTemps; will generate the following compiler errors: Test.javaz5: ']' expected double (7]{52] dailyTenps; Test. java:5: not a statement double [7] [52] dailyTenps; Test java:5: illegal start of expression int [7] [52] dailyTenps; Test.java:5: ';' expected int [7][52] dailyTemps; 9.1. Declaring and instantiating Multidimensional Arrays Test.java:5: not a statement int [7] [52] dailytenps; Test.Java:5: ';' expected int (7) [52] dailyTemps; Test.java:5: not a statement double [7] [52] dailyTenpss 7 errors 9.1.2 _Instantiating Multidimensional Arrays Just like instantiating single-dimensional arrays, you instantiate a multidi- mensional array using the new keyword. Here is the syntax for instantiating a two-dimensional array: arrayName = new datatype [exp1] [exp2] ; where expl and exp2 are expressions that evaluate to integers and specify, respectively, the number of rows and the number of columns in ‘the array. This statement allocates memory for the array. The number of elements in a two-dimensional array is equal to the sum of the number of elements in each row. When all the rows have the same number of columns, the num- ber of elements in the array is equal to the number of rows multiplied by the number of columns. For example, if we instantiate the following dailyTemps array with 52 rows and 7 columns, the array will have 52 * 7, or 364, elements: dailyTemps = new double [52][7]; // dailyTemps has 52 rows 1 and 7 columns, // for a total of 364 elements ‘These statements will instantiate the other arrays declared above: int nunberOfStudents = 253 ‘int nunberOfQuizzes = 10; quizzes = new char [nunberOfStudents] [nunberofquizzes] // quizzes has 25 rows and 10 columns // for a total of 250 elements cars = new Auto [5][50]; // cars has 5 rows and 50 colums // cars will store 250 Auto objects brian = new int [80] (20); ne msn 8 REFERENCE POINT Theintal values automati- cally given to arayele~ ‘ments depend onthe data type ofthe ara and are iscussedin Chapter8. CHAPTER? Multidimensional Arrays and the ArrayList Class // brian has 80 rows and 20 colums // there are 80 games per season // brian played baseball for 20 seasons jon = new int [80] [10] ; // Jon has 80 rows and 10 columns // jon played basebal1 for 10 seasons When a multidimensional array is instantiated, the elements are given ini- tial values automatically. Elements of arrays with numeric types are initial- ized to 0, elements of char type are initialized to the Unicode null character, elements of boolean type are initialized to false, and elements of class types are initialized to null 9.1.3 Combining the Declaration and Instantiation of Multidimensional Arrays Multidimensional arrays, like single-dimensional arrays, can also be instan- tiated when they are declared. To combine the declaration and instantia- tion of a two-dimensional array, use this syntax: datatype [ ][ ] arrayName = new datatype [expl] [exp2] where expl and exp2 are expressions that evaluate to integers and specify, respectively, the number of rows and columns in the array. ‘Thus, this statement: double [ ][ ] dailyTemps = new double [52] [ is equivalent to: double [ ][ ] dailyTempss dailytemps = new double [52] [7]; ‘Similarly, this statement: char [][ 1 quizzes = new char [25] [10]; is equivalent to: char [ J[ ] quizzes quizzes = new char [25] [10]; Furthermore, this statement: Auto [JE] cars = new Auto (5) [50]: is equivalent to: auto [IE] carss cars = new Auto [5}[50]}; 9.1 Declaring and Instantiating Multidimensional Arrays 9.1.4 Assigning Initial Values to Multidimensional Arrays We can instantiate a two-dimensional array by assigning initial values when the array is declared. To do this, we specify the initial values using comma- separated lists of initial values, enclosed in an outer set of curly braces: datatype [ J] arraytane = { { valued0, valueOl, ... }, { valuelo, valuell, }, ... 1s where valueMN is an expression that evaluates to the data type of the array and is the value to assign to the element at row M and column N. The list contains a number of sublists, separated by commas. The number of these sublists determines the number of rows in the array. For each row, the number of values in the corresponding sublist determines the number of columns in the row. Thus, Java allows a two-dimensional array to have a different number of columns in each row. For example, in our Auto array, each country (row) could have a different number of employees (columns) with company cars. Indeed, a two-dimensional array is an array of arrays. The first dimension of a two-dimensional array consists of an array of array references, with each reference pointing to a single-dimensional array. Thus, a two-dimen- sional array is composed of an array of rows, where each row is a single- dimensional array. Therefore, each row can have a different number of elements, or columns. For example, this statement declares and instantiates a two-dimensional array of integers: int C10] nunberstist ={ (0, 5, 10}, 10,369} Because two sublists are given, this two-dimensional array has two rows. The first sublist specifies three values, and therefore, the first row will have three columns; the second sublist specifies four values, and therefore, the second row will have four columns. Figure 9.2 shows the mumbersList] array after the preceding statement is executed. An initialization list can be given only when the array is declared. If a two- dimensional array has already been instantiated, attempting to assign values 33 msm Figue92 The numberslist? Array ‘After Instantiation CHAPTER ® Multidimensional Arrays and the ArrayList Class row {ol (0), fo) 11) {0} (2) row (1) [0] ay re) OB) to an array using an initialization list will generate a compiler error. For example, this code from the file Test.java: int [JE] grades = new int (2){3}; grades = { { 89, 73, 98 }, { 88, 65, 92) }5 will generate the following compiler errors: Test.java:6: illegal start of expression grades = { { 89, 73, 98 }, Test.java:6: not a statenent grades = { { 89, 73, 98 }, Test.java:6: ';' expected grades = { { 89, 73, 98}, Test. java:6: illegal start of expression grades = { { 89, 73, 98}, Test.java:7: not a statement { 88, 65, 92} }5 Test. jave " expected { 88, 65, 92} }s Test.java:9: class, interface, or enum expected } 7 errors We can declare and instantiate an array of objects by providing object references in the list: Auto sportsCar = new Auto( “Ferrari, 0, 0.0 ); ‘Auto sedanl = new Auto( "BMW", 0, 0.0 ); Auto sedans new Auto( "BMW", 100, 15.0 Auto sedan3 = new Auto( "Toyota", 0, 0.0 9.1. Dedaring and instantiating Multidimensional Arrays Auto rv1 = new Auto( “Jeep", 0, 0.0); Auto [ ][ ] cars = { { sportscar, sedanl }, { rvl, new Auto( ) }, { sedan2, sedan3 } }; array of Auto objects has three rows with two columns in each row. The elements of the array cars are object references to Auto objects. In most situations, the number of columns will be the same for each row. However, there are situations where itis useful to have a different number of columns for each row. For instance, Dr. Smith, a college professor, keeps track of grades using a two-dimensional array. The rows represent the courses she teaches and the columns represent the grades for the students in those sections. Grades are A, B, C, D, or F,so she declares the array with char elements. Dr. Smith teaches four courses: C$1, CS2, Database Man- agement, and Operating Systems. Thus, she has four rows in the array. But in each course, Dr. Smith has a different number of students: There are 23 students in CSI, 16 in CS2, 12 in Database Management, and 28 in Oper- ating Systems, So the first row will have 23 columns, the second row 16 columns, the third row 12 columns, and the fourth and last row will have 28 columns. Using an initialization list, it is easy to instantiate a two-dimensional array with a different number of columns for every row. But sometimes the data is retrieved dynamically—read from a file, for example—and it is not pos- sible to use an initialization list. ‘To instantiate a two-dimensional array with a different number of columns for each row, you can do the following: + First, instantiate the two-dimensional array. = Second, instantiate each row, as a single-dimensional array. For the preceding example, we can use the following code: char [ 1f ] grades; // declare the array grades = new char [4][]; // instantiate the array // grades has 4 null array elements grades(0] = new char [23]; // instantiate row 0; 23 char elenents grades(1] = new char [16]; // instantiate row 1; 16 char elenents grades[2] = new char [12]; // instantiate row 2; 12 char elenents grades[3] = new char [28]; // instantiate row 3; 28 char elements 35 COMMON ERROR TRAP An initialization listcan be ‘ven only when the two-

Вам также может понравиться