1 3 Array of Objects 1992 2007 Pearson

1 3 Array of Objects 1992 -2007 Pearson Education, Inc. All rights reserved.

2 OBJECTIVES In this chapter you will learn: § What arrays are. § To use arrays to store data in and retrieve data from lists and tables of values. § To declare an array, initialize an array and refer to individual elements of an array. § What are array of objects? § To use the enhanced for statement to iterate through arrays. § To pass arrays to methods. § To declare and manipulate multidimensional arrays. § To write methods that use variable-length argument lists. 1992 -2007 Pearson Education, Inc. All rights reserved.

3 3. 1 Introduction 3. 2 Arrays 3. 3 Declaring and Creating Arrays 3. 4 Examples Using Arrays 3. 5 Enhanced for Statement 3. 6 Array of Objcts 3. 7 Passing Arrays to Methods 3. 8 My. Array Class 3. 9 Multidimensional Arrays 3. 10 Case Study: Class Grade. Book Using a Two-Dimensional Array 3. 11 Variable-Length Argument Lists 1992 -2007 Pearson Education, Inc. All rights reserved.

4 3. 1 Introduction • Arrays – Data structures – Related data items of same type – Remain same size once created • Fixed-length entries 1992 -2007 Pearson Education, Inc. All rights reserved.

5 3. 2 Arrays • Array – Group of variables • Have same type – Reference type 1992 -2007 Pearson Education, Inc. All rights reserved.

6 Fig. 7. 1 | A 12 -element array. 1992 -2007 Pearson Education, Inc. All rights reserved.

7 3. 2 Arrays (Cont. ) • Index – – Also called subscript Position number in square brackets Must be positive integer or integer expression First element has index zero a = 5; b = 6; c[ a + b ] += 2; • Adds 2 to c[ 11 ] 1992 -2007 Pearson Education, Inc. All rights reserved.

8 Common Programming Error 3. 1 Using a value of type long as an array index results in a compilation error. An index must be an int value or a value of a type that can be promoted to int—namely, byte, short or char, but not long. 1992 -2007 Pearson Education, Inc. All rights reserved.

9 3. 2 Arrays (Cont. ) • Examine array c – c is the array name – c. length accesses array c’s length – c has 12 elements ( c[0], c[1], … c[11] ) • The value of c[0] is – 45 1992 -2007 Pearson Education, Inc. All rights reserved.

10 3. 3 Declaring and Creating Arrays • Declaring and Creating arrays – Arrays are objects that occupy memory – Created dynamically with keyword new int c[] = new int[ 12 ]; – Equivalent to int c[]; // declare array variable c = new int[ 12 ]; // create array • the [] following c indicate that – c is a variable refering to an array – or a reference variabe • in the assignment statement. Dc refers to a 12 integer element array – Default initial values • 0 for numerial variables: • false for boolean • null for reference types 1992 -2007 Pearson Education, Inc. All rights reserved.

11 3. 3 Declaring and Creating Arrays • We can create arrays of objects too String b[] = new String[ 100 ]; • this is possible • • double [] array 1, array 2; equivalent to double array 1{]; double array 2[]; or double[] array 1; double[] array 2; 1992 -2007 Pearson Education, Inc. All rights reserved.

12 Common Programming Error 3. 3 Declaring multiple array variables in a single declaration can lead to subtle errors. Consider the declaration int[] a, b, c; . If a, b and c should be declared as array variables, then this declaration is correct—placing square brackets directly following the type indicates that all the identifiers in the declaration are array variables. However, if only a is intended to be an array variable, and b and c are intended to be individual int variables, then this declaration is incorrect—the declaration int a[], b, c; would achieve the desired result. 1992 -2007 Pearson Education, Inc. All rights reserved.

13 3. 3 Declaring and Creating Arrays (cont. ) • Declaring arrays • Creating arrays • Initializing arrays • Manipulating array elements 1992 -2007 Pearson Education, Inc. All rights reserved.

14 3. 3 Declaring and Creating Arrays (cont. ) • Creating and initializing an array – Declare array – Create array – Initialize array elements 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline Declare array as an array of ints 15 Create 10 ints for array; each int is initialized to 0 by default Init. Array. java array. length returns length of array Line 8 Declare array as an array of ints Line 10 Create 10 ints for array; each int is initialized to 0 by default Line 15 array. length returns length of array Each int is initialized to 0 by default array[counter] returns int associated with index in array Line 16 array[counter] returns int associated with index in array Program output 1992 -2007 Pearson Education, Inc. All rights reserved.

16 1 // Fig. 7. 2: Init. Array. java 2 // Creating an array. 3 4 public class Init. Array 5 { 6 public static void main( String args[] ) 7 { 8 int array[]; // declare array named array 9 10 array = new int[ 10 ]; // create the space for array 11 12 System. out. printf( "%s%8 sn", "Index", "Value" ); // column headings 13 14 // output each array element's value 15 16 for ( int counter = 0; counter < array. length; counter++ ) System. out. printf( "%5 d%8 dn", counter, array[ counter ] ); 17 } // end main 18 } // end class Init. Array 1992 -2007 Pearson Education, Inc. All rights reserved.

17 output Index 0 1 2 3 4 5 6 7 8 9 Value 0 0 0 0 0 1992 -2007 Pearson Education, Inc. All rights reserved.
![18 int array[]; Declare array as an array of ints array = new int[ 18 int array[]; Declare array as an array of ints array = new int[](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-18.jpg)
18 int array[]; Declare array as an array of ints array = new int[ 10 ]; Create 10 ints for array; each int is initialized to 0 by default Each int is initialized to 0 by default 1992 -2007 Pearson Education, Inc. All rights reserved.

19 for ( int counter = 0; counter < array. length; counter++ ) array. length returns length of array System. out. printf( "%5 d%8 dn", counter, array[ counter ] ); array[counter] returns int associated with index in array 1992 -2007 Pearson Education, Inc. All rights reserved.

20 3. 3 Declaring and Creating Arrays (cont. ) • Using an array initializer – Use initializer list • Items enclosed in braces ({}) • Items in list separated by commas int n[] = { 10, 20, 30, 40, 50 }; – Creates a five-element array – Index values of 0, 1, 2, 3, 4 – Do not need keyword new 1992 -2007 Pearson Education, Inc. All rights reserved.

Declare array as an array of ints Outline 21 Compiler uses initializer list Init. Array. java to allocate array Line 9 Declare array as an array of ints Line 9 Compiler uses initializer list to allocate array Program output 1992 -2007 Pearson Education, Inc. All rights reserved.

22 1 2 // Fig. 7. 3: Init. Array. java // Initializing the elements of an array with an array initializer. 3 4 public class Init. Array { 6 public static void main( String args[] ) 7 { 8 // initializer list specifies the value for eachelement 9 10 11 12 13 14 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; System. out. printf( "%s%8 sn", "Index", "Value" ); // column headings // output each array element's value for ( int counter = 0; counter < array. length; counter++ ) 15 System. out. printf( "%5 d%8 dn", counter, array[ counter ] ); 16 } // end main 17 } // end class Init. Array 1992 -2007 Pearson Education, Inc. All rights reserved.

23 output Index 0 1 2 3 4 5 6 7 8 9 Value 32 27 64 18 95 14 90 70 60 37 1992 -2007 Pearson Education, Inc. All rights reserved.
![24 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 24 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60,](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-24.jpg)
24 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; // Declare array as an array of ints // Compiler uses initializer list to allocate array System. out. printf( "%s%8 sn", "Index", "Value" ); // output each array element's value for ( int counter = 0; counter < array. length; counter++ ) System. out. printf( "%5 d%8 dn", counter, array[ counter ] ); 1992 -2007 Pearson Education, Inc. All rights reserved.

25 3. 4 Examples Using Arrays (Cont. ) • Calculating a value to store in each array element – Initialize elements of 10 -element array to even integers 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 26 Init. Array. java Line 8 Declare constant variable Line 9 Declare and create array that contains 10 ints Line 13 Use array index to assign array Program output 1992 -2007 Pearson Education, Inc. All rights reserved.
![27 final int ARRAY_LENGTH = 10; // declare constant int array[] = new int[ 27 final int ARRAY_LENGTH = 10; // declare constant int array[] = new int[](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-27.jpg)
27 final int ARRAY_LENGTH = 10; // declare constant int array[] = new int[ ARRAY_LENGTH ]; // create array // calculate value for each array element for ( int counter = 0; counter < array. length; counter++ ) array[ counter ] = 2 + 2 * counter; System. out. printf( "%s%8 sn", "Index", "Value" ); // output each array element's value for ( int counter = 0; counter < array. length; counter++ ) System. out. printf( "%5 d%8 dn", counter, array[ counter ] ); 1992 -2007 Pearson Education, Inc. All rights reserved.

28 output Index 0 1 2 3 4 5 6 7 8 9 Value 2 4 6 8 10 12 14 16 18 20 1992 -2007 Pearson Education, Inc. All rights reserved.

29 • Constant variables also are called named constants or read-only variables. Such variables often make programs more readable than programs that use literal values (e. g. , 10)—a named constant such as ARRAY_LENGTH clearly indicates its purpose, whereas a literal value could have different meanings based on the context in which it is used. 1992 -2007 Pearson Education, Inc. All rights reserved.

30 Common Programming Error 3. 4 Assigning a value to a constant after the variable has been initialized is a compilation error. 1992 -2007 Pearson Education, Inc. All rights reserved.

31 Common Programming Error 3. 5 Attempting to use a constant before it is initialized is a compilation error. 1992 -2007 Pearson Education, Inc. All rights reserved.

32 Getting the elements of an array from The user 1992 -2007 Pearson Education, Inc. All rights reserved.

33 Scanner input = new Scanner(System. in); final int ARRAY_LENGTH = 10; // declare constant int array[] = new int[ ARRAY_LENGTH ]; // create array // get th value for each array element from user for ( int counter = 0; counter < array. length; counter++ ){ System. out. print(“Enter ” + counter + “th element: ”); array[ counter ] =input. next. Int(); } // rest of the program is th same 1992 -2007 Pearson Education, Inc. All rights reserved.

34 3. 4 Examples Using Arrays (Cont. ) • Summing the elements of an array – Array elements can represent a series of values • We can sum these values 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 35 Sum. Array. java Line 8 Declare array with initializer list Lines 12 -13 Sum all array values Program output 1992 -2007 Pearson Education, Inc. All rights reserved.
![36 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 36 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76,](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-36.jpg)
36 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // add each element's value to total for ( int counter = 0; counter < array. length; counter++ ) total += array[ counter ]; System. out. printf( "Total of array elements: %dn", total ); 1992 -2007 Pearson Education, Inc. All rights reserved.

37 output Total of array elements: 849 1992 -2007 Pearson Education, Inc. All rights reserved.

38 3. 5 Enhanced for Statement • Enhanced for statement – Iterates through elements of an array or a collection without using a counter – Syntax for ( parameter : array. Name ) statement 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 39 Enhanced. For. Test. java 1992 -2007 Pearson Education, Inc. All rights reserved.
![40 3. 5 Enhanced for Statement (Cont. ) int array[] = { 87, 68, 40 3. 5 Enhanced for Statement (Cont. ) int array[] = { 87, 68,](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-40.jpg)
40 3. 5 Enhanced for Statement (Cont. ) int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // add each element's value to total for ( int number : array ) total += number; System. out. printf( "Total of array elements: %dn", total ); output Total of array elements: 849 1992 -2007 Pearson Education, Inc. All rights reserved.

41 3. 5 Enhanced for Statement (Cont. ) • equivalent to for ( int counter = 0; counter < array. length; counter++ ) total += array[ counter ]; • Usage and limitations – Can only access array elements (read only) • can appear only on the left side of assignment statments in the body of the loop – Cannot modify array elements – Cannot access the counter indicating the index • traverese the entire array or collection • cannot skip some part of the array e. g. : only even indexed elements 1992 -2007 Pearson Education, Inc. All rights reserved.

42 3. 6 Array of Objects • Array elements can refer to objects • then they are references to objects Product[] products = new Product[4]; • products is a reference refereing to an array contaiing 4 references to objects from the Product class. • after this statement elements of the products array are initilized to their default values – null • no Product objects are created yet 1992 -2007 Pearson Education, Inc. All rights reserved.

43 3. 6 Array of Objects (cont. ) • after initilizing the products array with null values • create Product objects and assing them to individual elements of the products array • let individual elements of the products array refer to these product objects 1992 -2007 Pearson Education, Inc. All rights reserved.

44 class Product public class Product { private String name; private double price; private int amount; public Product(Sting n, double p, int a) { name = n; set. Price(p); set. Amount(a); } // end constructor // add set get methds } // end class Product 1992 -2007 Pearson Education, Inc. All rights reserved.

45 class Array. Of. Objects public class Array. Of. Objects { public static void main(String args[]) { // create products array with 3 references to // product objects Product[] products = new Product[3]; // create products and attach to the array products[0] = new Product(“table”, 100, 10); products[1] = new Product(“chair”, 75, 5); products[2] = new Product(”board”, 200, 3); // total value of products double total = 0. 0; for(int i = 0; i< products. length; i++) total += products[i]. get. Price()* products[i]. get. Amount(); } // end main } end class 1992 -2007 Pearson Education, Inc. All rights reserved.

46 Explanations • treditional for loop can be converted to an enhenced for as follows: for(int e: products) total += e. get. Price()* e. get. Amount(); • if some of the elements of the products array are null – not assigned any products • previous loops produces null pointer exceptions • how to fix this potential error for(int e: products) if(e !=null) total += e. get. Price()* e. get. Amount(); 1992 -2007 Pearson Education, Inc. All rights reserved.

47 just after declaring and initilizing array products null 1992 -2007 Pearson Education, Inc. All rights reserved.

just product objects created and assigned 48 products board null table 1992 -2007 Pearson Education, Inc. All rights reserved.

49 3. 7 Passing Arrays to Methods • To pass array argument to a method – Specify array name without brackets • Array hourly. Temperatures is declared as int hourly. Temperatures = new int[ 24 ]; • The method call modify. Array( hourly. Temperatures ); • Passes array hourly. Temperatures to method modify. Array 1992 -2007 Pearson Education, Inc. All rights reserved.

Declare 5 -int array with initializer list Outline 50 Pass. Array. java (1 of 2) Pass entire array to method Line 9 modify. Array Line 19 1992 -2007 Pearson Education, Inc. All rights reserved.
![Pass array element array[3] to method modify. Element Outline 51 Pass. Array. java Method Pass array element array[3] to method modify. Element Outline 51 Pass. Array. java Method](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-51.jpg)
Pass array element array[3] to method modify. Element Outline 51 Pass. Array. java Method modify. Array manipulates the array directly (2 of 2) Method modify. Element manipulates a primitive’s copy Line 30 Lines 36 -40 Lines 43 -48 Program output 1992 -2007 Pearson Education, Inc. All rights reserved.

52 Example // Fig. 7. 13: Pass. Array. java // Passing arrays and individual array elements to methods. public class Pass. Array { // main creates array and calls modify. Array and modify. Element public static void main( String args[] ) { int array[] = { 1, 2, 3, 4, 5 }; System. out. println( "Effects of passing reference to entire array: n" + "The values of the original array are: " ); // output original array elements for ( int value : array ) System. out. printf( " %d", value ); 1992 -2007 Pearson Education, Inc. All rights reserved.

53 Example (cont. ) modify. Array( array ); // pass array reference System. out. println( "nn. The values of the modified array are: " ); // output modified array elements for ( int value : array ) System. out. printf( " %d", value ); System. out. printf( "nn. Effects of passing array element value: n" + "array[3] before modify. Element: %dn", array[ 3 ] ); modify. Element( array[ 3 ] ); // attempt to modify array[ 3 ] System. out. printf( "array[3] after modify. Element: %dn", array[ 3 ] ); } // end main 1992 -2007 Pearson Education, Inc. All rights reserved.

54 Example (cont. ) // multiply each element of an array by 2 public static void modify. Array( int array 2[] ) { for ( int counter = 0; counter < array 2. length; counter++ ) array 2[ counter ] *= 2; } // end method modify. Array // multiply argument by 2 public static void modify. Element( int element ) { element *= 2; System. out. printf( "Value of element in modify. Element: %dn", element ); } // end method modify. Element } // end class Pass. Array 1992 -2007 Pearson Education, Inc. All rights reserved.

55 output Effects of passing reference to entire array: The values of the original array are: 1 2 3 4 5 The values of the modified array are: 2 4 6 8 10 Effects of passing array element value: array[3] before modify. Element: 8 Value of element in modify. Element: 16 array[3] after modify. Element: 8 1992 -2007 Pearson Education, Inc. All rights reserved.
![56 Explanations int array[] = { 1, 2, 3, 4, 5 }; Declare 5 56 Explanations int array[] = { 1, 2, 3, 4, 5 }; Declare 5](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-56.jpg)
56 Explanations int array[] = { 1, 2, 3, 4, 5 }; Declare 5 -int array with initializer list modify. Array( array ); Pass entire array to method modify. Array modify. Element( array[ 3 ] ); Pass array element array[3] to method modify. Element 1992 -2007 Pearson Education, Inc. All rights reserved.
![57 public static void modify. Array( int array 2[] ) Method modify. Array manipulates 57 public static void modify. Array( int array 2[] ) Method modify. Array manipulates](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-57.jpg)
57 public static void modify. Array( int array 2[] ) Method modify. Array manipulates the array directly public static void modify. Element( int element ) Method modify. Element manipulates a primitive’s copy 1992 -2007 Pearson Education, Inc. All rights reserved.

58 3. 7 Passing Arrays to Methods (Cont. ) • Notes on passing arguments to methods – Two ways to pass arguments to methods • Pass-by-value – Copy of argument’s value is passed to called method – Every primitive type is passed-by-value • Pass-by-reference – Caller gives called method direct access to caller’s data – Called method can manipulate this data – Improved performance over pass-by-value – Every object is passed-by-reference • Arrays are objects • Therefore, arrays are passed by reference 1992 -2007 Pearson Education, Inc. All rights reserved.

59 Performance Tip 3. 1 Passing arrays by reference makes sense for performance reasons. If arrays were passed by value, a copy of each element would be passed. For large, frequently passed arrays, this would waste time and consume considerable storage for the copies of the arrays. 1992 -2007 Pearson Education, Inc. All rights reserved.

60 3. 8 A generic array class • Develop a gneric array class called My. Array • including many methods for – geting arrays – printing the array – calculating sum, average, standard deviation, minimum, maximum, . . – modifying arrays: multiply by two store in another array – finding distinct values of arrays – sorting, searching in arrays – fining union, intersetion of two arrays 1992 -2007 Pearson Education, Inc. All rights reserved.
![61 class My. Array public class My. Array { private int[] my. Array; // 61 class My. Array public class My. Array { private int[] my. Array; //](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-61.jpg)
61 class My. Array public class My. Array { private int[] my. Array; // constructor public My. Array(int[] the. Array) { my. Array = the. Array; // initialized elsewhere in another class // just pass the reference } 1992 -2007 Pearson Education, Inc. All rights reserved.

62 class My. Array – method maximum public int maximum() { int max = my. Array[0]; for(int e : my. Array) // loop over elements if(e > max) // here e represent the element max = e; return max; } 1992 -2007 Pearson Education, Inc. All rights reserved.

63 class My. Array – method max. Position public int max. Position() { int max = my. Array[0]; int position = 0; for(int i=0; i < my. Array. length; i++) // loop over index if(my. Array[i] > max) // i is the index of the array { max = my. Array[i]; position = i; } return position; } 1992 -2007 Pearson Education, Inc. All rights reserved.

64 class My. Array – method display public void display() { for(int e: my. Array) System. out. printf(“%10 d”, e); } 1992 -2007 Pearson Education, Inc. All rights reserved.

65 class My. Array – method multiply 0 public void multiply 0(int k) { int n = my. Array. length; // elemements of my. Array are multiply by k for(int i = 0; i < n; i++) my. Array[i] = my. Array[i]*k; } 1992 -2007 Pearson Education, Inc. All rights reserved.
![66 class My. Array – method multiply 1 public int[] multiply 1(int k) { 66 class My. Array – method multiply 1 public int[] multiply 1(int k) {](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-66.jpg)
66 class My. Array – method multiply 1 public int[] multiply 1(int k) { int n = my. Array. length; // a new array of the same length as my. Array int[] c = new int[n]; for(int i = 0; i < n; i++) c[i] = my. Array[i]*k; return c; } 1992 -2007 Pearson Education, Inc. All rights reserved.
![67 class My. Array – method add 1 public int[] add 1(int[] b) { 67 class My. Array – method add 1 public int[] add 1(int[] b) {](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-67.jpg)
67 class My. Array – method add 1 public int[] add 1(int[] b) { int n = my. Array. length; if(b == null) return null; int m = b. length; if(n != m) return null; // a new array of the same length as my. Array and b int[] c = new int[n]; for(int i = 0; i < n; i++) c[i] = my. Array[i]+b[i]; return c; } 1992 -2007 Pearson Education, Inc. All rights reserved.
![68 class My. Array – method add 2 public int[] add 2(My. Array my. 68 class My. Array – method add 2 public int[] add 2(My. Array my.](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-68.jpg)
68 class My. Array – method add 2 public int[] add 2(My. Array my. A) { return add 1(my. Array); } 1992 -2007 Pearson Education, Inc. All rights reserved.

69 class My. Array – method add 13 public My. Array add 3(My. Array my. A) { return new My. Array(add 2(my. A); } 1992 -2007 Pearson Education, Inc. All rights reserved.

70 class Test. My. Array public class Test. My. Array { public static void main(String args[]) { int[] array 1 = {1, 2, 3}; int[] array 2 = {4, 5, 6}; My. Array my. Ar 1 = new My. Array(array 1); My. Array my. Ar 2 = new My. Array(array 2); my. Ar 1. display(); int max 1 = my. Ar 1. maximum(); my. Ar 1. multiply 0(3); int[] c 0 = my. Ar 1. multiply 1(3); int[] c 1 = my. Ar 1. add 1(array 2); int[] c 2 = my. Ar 1. add 2(my. Ar 2); My. Array my. Ar 3 = my. Ar 1. add 3(my. Ar 2); } // end main } // end test class 1992 -2007 Pearson Education, Inc. All rights reserved.

71 Explanations • this methods take an array and return its maximum or position of the maximum value as an intger primitive variable • How to call such methods in another class int[] a = {1, 2, 3, 4, 5}; // create a my. A type object sening array a to its constructor My. Array my. A = new My. Array(a); // initilize my. A // call the maximum method of over my. A int max. Ofa = my. A. maximum(); int pos. Max = my. A. max. Position(); 1992 -2007 Pearson Education, Inc. All rights reserved.

72 Procedural approach A procedural approach for such mehods is declaring each method in the same class as arrays are defined 1992 -2007 Pearson Education, Inc. All rights reserved.
![73 public class Array. Metods. Procedural { public static void main(String args[]) { int[] 73 public class Array. Metods. Procedural { public static void main(String args[]) { int[]](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-73.jpg)
73 public class Array. Metods. Procedural { public static void main(String args[]) { int[] a = {1. 2. 3. 4. 5}; int max. Of. A = maximum(a); int pos. Of. A = max. Position(a); // print these } // end of main method 1992 -2007 Pearson Education, Inc. All rights reserved.
![74 public static int maximum( int[] my. Array) { int max = my. Array[0]; 74 public static int maximum( int[] my. Array) { int max = my. Array[0];](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-74.jpg)
74 public static int maximum( int[] my. Array) { int max = my. Array[0]; for(int i : my. Array) // loop over elements if(i > max) // here i represent the element max = i; return max; } // end of maximum // write the max. Position method as an exercise } end of class array. Methods. Procedural 1992 -2007 Pearson Education, Inc. All rights reserved.

75 A generic array class • Methods may also return arrays as rferences – what if thee are more then one maximum value in an array how can the possition of each can be returned – e. g. a = {1, 2, 5, 1, 5} – maximum value is 5 its positions are 2 and 4 – so an array returning positions should be {2, 4} • Other examples – – copying an array finding unions, intersection of arrays inverting an array – reversing its elements Searching arrays 1992 -2007 Pearson Education, Inc. All rights reserved.

76 A generic array class • • Example inverting an array elements a = {2. 4. 6. 2. 5} ainv = {5. 2. 6. 4. 2} a method that takes as the original array and modifys the original array • a method that takes the original array and returns a new invered array • a method that takes the original array and another array as parameters and modify the second array • a method that creates a My. Array objcet and initialize it with the inverted array returning the reference of the My. Array objcet 1992 -2007 Pearson Education, Inc. All rights reserved.
![77 A generic array class public static void invert 1(int[] array) { int temp, 77 A generic array class public static void invert 1(int[] array) { int temp,](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-77.jpg)
77 A generic array class public static void invert 1(int[] array) { int temp, n = array. length; for( int i = 0 ; i <= n/2 -1 ; i++ ) { temp = array[i]; array[i] = array[n-i-1] = ; array[n-i-1] = temp; } // end of for loop } // end of method 1992 -2007 Pearson Education, Inc. All rights reserved.
![78 A generic array class public static int[] invert 2(int[] array ) { int 78 A generic array class public static int[] invert 2(int[] array ) { int](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-78.jpg)
78 A generic array class public static int[] invert 2(int[] array ) { int n = array. length; int[] inv. Array = new int[n]; for( int i = 0 ; i < n ; i++ ) inv. Array[i] = array[n-i-1]; return inv. Array; } // end of method 1992 -2007 Pearson Education, Inc. All rights reserved.
![79 A generic array class public static void invert 3(int[] array, int[] inv. Array 79 A generic array class public static void invert 3(int[] array, int[] inv. Array](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-79.jpg)
79 A generic array class public static void invert 3(int[] array, int[] inv. Array ) { int n = array. length; inv. Array = new int[n]; for( int i = 0 ; i < n ; i++ ) inv. Array[i] = array[n-i-1]; } // end of method 1992 -2007 Pearson Education, Inc. All rights reserved.

80 A generic array class public class Invert. Static { public static void main(String args[]) [ int[] a = {1. 4. 3. 7. 6}; invert 1(a); // display array a it is inverted int b[] = new int[a. length]; // same lenght as array a invert 3(a, b); // display a and b // b is the original array int[] c = invert 2(a); // print c } // end of main method 1992 -2007 Pearson Education, Inc. All rights reserved.

81 non static versions the non static versions of the invert 1, invert 2 and invert 3 methods are called over objcets say lets create My. Array type objects and call these methods on these objcets 1992 -2007 Pearson Education, Inc. All rights reserved.
![82 public class My. Array { int[] my. Array; public My. Array(int[] my. Array) 82 public class My. Array { int[] my. Array; public My. Array(int[] my. Array)](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-82.jpg)
82 public class My. Array { int[] my. Array; public My. Array(int[] my. Array) { this. my. Array = my. Array; } 1992 -2007 Pearson Education, Inc. All rights reserved.

83 // invert 1 has no parameter and retrurn no parameter // takes the instance variable my. Array and inverts it public void invert 1() { int temp, n = my. Array. length; for( int i = 0 ; i <= n/2 -1 ; i++ ) { temp = my. Array[i]; my. Array[i] = my. Array[n-i-1]; my. Array[n-i-1] = temp; } // end of for loop } // end of method 1992 -2007 Pearson Education, Inc. All rights reserved.

84 calling invert 1 from another class public class Invert. Test {ddyt public static void main(String args[]) { int[] a = {1, 4, 2, 5, 9}; My. Array my. A = new My. Array(a); my. A. invert 1(); // display array a it is inverted } 1992 -2007 Pearson Education, Inc. All rights reserved.
![85 other methods of the My. Array class public class My. Array { int[] 85 other methods of the My. Array class public class My. Array { int[]](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-85.jpg)
85 other methods of the My. Array class public class My. Array { int[] my. Array; public My. Array(int[] my. Array) { this. my. Array = my. Array; } public void invert 1() {. . . } 1992 -2007 Pearson Education, Inc. All rights reserved.
![86 public int[] invert 2() { int n = my. Array. length; int[] inv. 86 public int[] invert 2() { int n = my. Array. length; int[] inv.](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-86.jpg)
86 public int[] invert 2() { int n = my. Array. length; int[] inv. Array = new int[n]; for( int i = 0 ; i < n ; i++ ) inv. Array[i] = my. Array[n-i-1]; return inv. Array; } // end of method 1992 -2007 Pearson Education, Inc. All rights reserved.

87 how to call invert 2 from main public class Invert. Test { public static void main(String args[]) { int[] a = {1, 4, 2, 5, 9}; My. Array my. A = new My. Array(a); int[] b = my. A. invert 2(); // display array b it is inverted version of array a } // end of main } // end of calss Invert. Test 1992 -2007 Pearson Education, Inc. All rights reserved.

88 finding the position of maximum add another method to the My. Array class so that it will return the indesis of the maximum element in an array there may be more then one index so the return type should be an array whose length is equal or shorther then the original array 1992 -2007 Pearson Education, Inc. All rights reserved.
![89 public class My. Array { int[] my. Array; // constructor and other methods 89 public class My. Array { int[] my. Array; // constructor and other methods](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-89.jpg)
89 public class My. Array { int[] my. Array; // constructor and other methods 1992 -2007 Pearson Education, Inc. All rights reserved.
![90 public int[] max. Position(); { int[] postemp = new int[my. Array. length] int 90 public int[] max. Position(); { int[] postemp = new int[my. Array. length] int](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-90.jpg)
90 public int[] max. Position(); { int[] postemp = new int[my. Array. length] int max=my. Array[0], n. Pos = -1; for(int i=0; i<my. Array. length; i++) { if(my. Array[i] > max) { max = my. Array[i]; n. Pos = 0; postemp[n. Pos] = i; } else if (my. Array[i] == max) { n. Pos++; postemp[n. Pos] = i; } 1992 -2007 Pearson Education, Inc. All rights reserved.
![91 int[] positions = new int[n. Pos+1]; // copy the temorary array to the 91 int[] positions = new int[n. Pos+1]; // copy the temorary array to the](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-91.jpg)
91 int[] positions = new int[n. Pos+1]; // copy the temorary array to the position array for(int i = 0; i < positions. lentgth; i++) positions[i] = postemp[i]; return positions; } // end of method 1992 -2007 Pearson Education, Inc. All rights reserved.

92 Searching in an array Linear search Add as a method to My. Array class Take the input a key an integer to be searched in the instance variable of My. Array class if found return the possition of the key if not fournd return -1 1992 -2007 Pearson Education, Inc. All rights reserved.

93 public int linear. Search(int key) { // loop through array sequentially for (int i = 0 ; i < my. Array. length ; i++ ) if ( my. Array[i] == key ) return i; // return index of integer return -1; // integer not found in array } // end of method 1992 -2007 Pearson Education, Inc. All rights reserved.

94 Test class for linear search import java. util. Scanner public class Linear. Search. Test { public static void main(String args[]) { int[] a = {1, 4, 2, 5, 9}; My. Array my. A = new My. Array(a); // get a key from the user; Scanner input = new Scanner(System. in); System. out. print(“Enter the key: ”); int search. Key = input. next. Int(); // search the key in the array int search. Res = my. A. linear. Search(search. Key); // display search results } // end of main } // end class 1992 -2007 Pearson Education, Inc. All rights reserved.

95 Exercise • This version of the linear search method is restricted • If the search key occors more then one possition in the array all of these should be returned – – – As an array of possitions a = {2, 4, 2, 5, 2} key =2 then Return {0, 2, 4} possition array key =7 Return {-1} key not fournd 1992 -2007 Pearson Education, Inc. All rights reserved.

96 3. 9 Multidimensional Arrays public class copy. Array. Test { public static void main(. . ) { int[] a = {1, 2, 3}; int [] b = copy. Array(a); // print. . . } // end of main public static int[] copy. Array(int a[]) { int[] b = new int[a. length]; for(int i = 0 ; i < a. length ; i++) b[i] = a[i]; return b; } // end of method } // end of class 1992 -2007 Pearson Education, Inc. All rights reserved.

97 3. 9 Multidimensional Arrays • Multidimensional arrays – Tables with rows and columns • Two-dimensional array • m-by-n array 1992 -2007 Pearson Education, Inc. All rights reserved.

98 Fig. 7. 16 | Two-dimensional array with three rows and four columns. 1992 -2007 Pearson Education, Inc. All rights reserved.

99 3. 9 Multidimensional Arrays (Cont. ) • Arrays of one-dimensional array – Declaring two-dimensional array b[2][2] int b[][] = { { 1, 2 }, { 3, 4 } }; – 1 and 2 initialize b[0][0] and b[0][1] – 3 and 4 initialize b[1][0] and b[1][1] int b[][] = { { 1, 2 }, { 3, 4, 5 } }; – row 0 contains elements 1 and 2 – row 1 contains elements 3, 4 and 5 1992 -2007 Pearson Education, Inc. All rights reserved.

100 3. 9 Multidimensional Arrays (Cont. ) • Two-dimensional arrays with rows of different lengths – Lengths of rows in array are not required to be the same • E. g. , int b[][] = { { 1, 2 }, { 3, 4, 5 } }; 1992 -2007 Pearson Education, Inc. All rights reserved.

101 3. 9 Multidimensional Arrays (Cont. ) • Creating two-dimensional arrays with arraycreation expressions – 3 -by-4 array int b[][]; b = new int[ 3 ][ 4 ]; – Rows can have different number of columns int b[][]; b = new int[ 2 ][ ]; // create 2 rows b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 102 Init. Array. java (1 of 2) Line 9 Line 10 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 103 Init. Array. java (2 of 2) Line 26 Line 27 Program output 1992 -2007 Pearson Education, Inc. All rights reserved.

104 3. 9 Multidimensional Arrays (Cont. ) • Common multidimensional-array manipulations performed with for statements – Many common array manipulations use for statements E. g. , for ( int column = 0; column < a[ 2 ]. length; column++ ) a[ 2 ][ column ] = 0; 1992 -2007 Pearson Education, Inc. All rights reserved.
![105 public class My 2 Dim. Array { int[][] two. Dim. Array; // constructor 105 public class My 2 Dim. Array { int[][] two. Dim. Array; // constructor](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-105.jpg)
105 public class My 2 Dim. Array { int[][] two. Dim. Array; // constructor public My 2 Dim. Array(int[][] new. Array) { two. Dim. Array = new. Array; } 1992 -2007 Pearson Education, Inc. All rights reserved.
![106 public int[] row. Sum() { int sum; int n = two. Dim. Array. 106 public int[] row. Sum() { int sum; int n = two. Dim. Array.](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-106.jpg)
106 public int[] row. Sum() { int sum; int n = two. Dim. Array. length; int[] sum. Of. Raws = new int [n]; for ( int i = 0 ; i < n ; i++ ) { sum = 0; for(int j = 0 ; j < two. Dim. Array[i]. length ; j++ ) sum += two. Dim. Array[i][j]; sum. Of. Raws[i] = sum; } // end of outer loop return sum. Of. Raws; } // end of method 1992 -2007 Pearson Education, Inc. All rights reserved.
![107 Sum of columns if array is regtangular public int[] column. Sum() { int 107 Sum of columns if array is regtangular public int[] column. Sum() { int](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-107.jpg)
107 Sum of columns if array is regtangular public int[] column. Sum() { int sum; int n = two. Dim. Array[0]. length; int m = two. Dim. Array. length; int[] sum. Of. Columns = new int [n]; for ( int i = 0 ; i < n ; i++ ) { sum = 0; for(int j = 0 ; j < m ; j++ ) sum += two. Dim. Array[j][i]; sum. Of. Columns[i] = sum; } // end of outer loop return sum. Of. Raws; } // end of method 1992 -2007 Pearson Education, Inc. All rights reserved.

108 Exercise • Write a version of the column sum method for arrays whose number of elements in each row is not equal – They are not regtangular arrays • E. g. : array = {{1, 3}, • {2, 6, 4}, • {2} } • sum. Of. Raws = {5, 9, 4} 1992 -2007 Pearson Education, Inc. All rights reserved.
![109 public double[] raw. Averages() { double[] ave = new double[two. Dim. Array. length]; 109 public double[] raw. Averages() { double[] ave = new double[two. Dim. Array. length];](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-109.jpg)
109 public double[] raw. Averages() { double[] ave = new double[two. Dim. Array. length]; for ( int i = 0 ; i < two. Dim. Array. length ; i++ ) ave[i] = get. Average(two. Dim. Array[i]); return ave; } public double get. Average(int a[]) { int sum = 0; for(int element : a ) sum += element; return (double) sum / a. length; } 1992 -2007 Pearson Education, Inc. All rights reserved.
![110 public int[] column. Max() {. . . } public int[] raw. Max() {. 110 public int[] column. Max() {. . . } public int[] raw. Max() {.](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-110.jpg)
110 public int[] column. Max() {. . . } public int[] raw. Max() {. . . } Write their column. Min and raw. Min versions as well 1992 -2007 Pearson Education, Inc. All rights reserved.
![111 public int[][] transpose() { int n = two. Dim. Array. length; int m 111 public int[][] transpose() { int n = two. Dim. Array. length; int m](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-111.jpg)
111 public int[][] transpose() { int n = two. Dim. Array. length; int m = two. Dim. Array[0]. length; int[][] transpose = new int[m][n]; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++ ) transpose[j][i] = two. Dim. Array[i][j]; return transpose; } 1992 -2007 Pearson Education, Inc. All rights reserved.

112 İs. Rectenge method is rectengle is a boolean method returns true or false Check whether the instance variable of the two. Dim. Array class is a regtengular array or not A two dimensional array to be a rectenge: length of each raw should be the same length of raw 0 = length of raw 1 length of raw 0 = length of raw 2 length of raw 0 = length of raw 3. . . 1992 -2007 Pearson Education, Inc. All rights reserved.

113 public boolean is. Rectenge() { boolean is. Rect = true; int n = two. Dim. Array. length; int m = two. Dim. Array[0]. length; int i = 1; while(is. Rect && i < n) { is. Rect = (two. Dim. Array[i]. length == m) && is. Rect; i++; } ret 1 urn is. Rect; } 1992 -2007 Pearson Education, Inc. All rights reserved.

Another version of the is. Rectange method 114 public boolean is. Rectenge() { boolean is. Rect = true; int n = two. Dim. Array. length; int m = two. Dim. Array[0]. length; int i = 0; while(is. Rect && ++i < n) is. Rect &= (two. Dim. Array[i]. length == m); ret 1 urn is. Rect; } 1992 -2007 Pearson Education, Inc. All rights reserved.

115 Adding two matrisis a and b • Part of the My 2 Dim. Array class • Called on an objcet add the instance variable to the parameter of the method 1992 -2007 Pearson Education, Inc. All rights reserved.
![116 public int[][] add(int b[][]) { int n = tw. Dim. Array. length; int 116 public int[][] add(int b[][]) { int n = tw. Dim. Array. length; int](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-116.jpg)
116 public int[][] add(int b[][]) { int n = tw. Dim. Array. length; int m = two. Dim. Array[0]. length; int[][] c = new[n][m]; for (int i =0 ; i < n ; i++) for (int j =0 ; j < m ; j++) c[i][j] = two. Dim. Array[i][j] + b[i][j]; return c; } // end of method 1992 -2007 Pearson Education, Inc. All rights reserved.

117 Exercise • Write a method of the My 2 Dim. Array class for matrix multiplication – Check the dimensionality condition for the two matrisis and if the are not appropriate return a null reference 1992 -2007 Pearson Education, Inc. All rights reserved.
![118 public class two. Dim. Array. Test { public static void main(String args[]) { 118 public class two. Dim. Array. Test { public static void main(String args[]) {](http://slidetodoc.com/presentation_image_h/1d90a6f3e51fa4b24689fdbedde9aeea/image-118.jpg)
118 public class two. Dim. Array. Test { public static void main(String args[]) { int[][] a = {{2, 4, 6}, {5, 1, 7}}; Two. Dim. Array my 2 Dim = new Two. Dim. Array(a); } } 1992 -2007 Pearson Education, Inc. All rights reserved.

119 1992 -2007 Pearson Education, Inc. All rights reserved.

3. 10 Case Study: Class Grade. Book Using a Two-Dimensional Array 120 • Class Grade. Book – One-dimensional array • Store student grades on a single exam – Two-dimensional array • Store grades for a single student and for the class as a whole 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 121 Declare two-dimensional array grades Grade. Book. java (1 of 7) Line 7 Grade. Book constructor accepts a String and a two-dimensional array Line 10 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 122 Grade. Book. java (2 of 7) 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline Loop through rows of grades to find the lowest grade of any student 123 Grade. Book. java (3 of 7) Lines 58 -67 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline Loop through rows of grades to find the highest grade of any student 124 Grade. Book. java (4 of 7) Lines 79 -88 Lines 94 -104 Calculate a particular student’s semester average 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 125 Grade. Book. java (5 of 7) Lines 115 -119 Calculate the distribution of all student grades 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 126 Grade. Book. java (6 of 7) 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 127 Grade. Book. java (7 of 7) 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 128 Declare grades. Array as 10 by-3 array Grade. Book. Test. java (1 of 2) Lines 10 -19 Each row represents a student; each column represents an exam grade 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 129 Grade. Book. Test. java (2 of 2) Program output 1992 -2007 Pearson Education, Inc. All rights reserved.

130 3. 11 Variable-Length Argument Lists • Variable-length argument lists – Unspecified number of arguments – Use ellipsis (…) in method’s parameter list • Can occur only once in parameter list • Must be placed at the end of parameter list – Array whose elements are all of the same type 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 131 Varargs. Test. java (1 of 2) Line 7 Lines 12 -13 Line 15 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline 132 Varargs. Test. java (2 of 2) Line 29 Line 31 Line 33 Program output 1992 -2007 Pearson Education, Inc. All rights reserved.

133 Common Programming Error 3. 6 Placing an ellipsis in the middle of a method parameter list is a syntax error. An ellipsis may be placed only at the end of the parameter list. 1992 -2007 Pearson Education, Inc. All rights reserved.
- Slides: 133