Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 7 – Arrays and Array Lists.

Similar presentations


Presentation on theme: "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 7 – Arrays and Array Lists."— Presentation transcript:

1 Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 7 – Arrays and Array Lists

2 Copyright © 2014 by John Wiley & Sons. All rights reserved.2 Chapter Goals  To collect elements using arrays and array lists  To use the enhanced for loop for traversing arrays and array lists  To learn common algorithms for processing arrays and array lists  To work with two-dimensional arrays  To understand the concept of regression testing

3 Copyright © 2014 by John Wiley & Sons. All rights reserved.3 Arrays  An array collects a sequence of values of the same type.  E.g. Create an array that can hold ten values of type double: new double[10] The number of elements is the length of the array The new operator constructs the array  The type of an array variable is the type of the element to be stored, followed by [].

4 Copyright © 2014 by John Wiley & Sons. All rights reserved.4 Arrays  To declare an array variable of type double[] double[] values;  To initialize the array variable with the array: double[] values = new double[10];  By default, each number in the array is 0 values 0000000000 0123456789 Index values First index is always 0 Last index is always length-1

5 Copyright © 2014 by John Wiley & Sons. All rights reserved.5  Element types can be anything (basic data type/object) Student[] students= new Student[3]; students 012 Student Object 1 Student Object 2 Student Object 3

6 Copyright © 2014 by John Wiley & Sons. All rights reserved.6 Initializing array element values  Method 1: You can specify the initial values when you create the array double[] moreValues = { 32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 }; You don’t need to specify number of elements.  Method 2: use the [] operator Specify index of element values[4] = 35; 325467.529358011544.510065 0123456789 00003500000 0123456789

7 Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Accessing Array Elements  Specify index within [] operator System.out.println(values[4]); Result = 10.0 + values[2];  Each index position uniquely identifies an element.  Individual elements are accessed by an integer index i, using the notation array[i] where array is the array name  An array element can be used like any variable. System.out.println(values[4]);

8 Copyright © 2014 by John Wiley & Sons. All rights reserved.8 Arrays Figure 1 An Array of Size 10

9 Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Syntax 7.1 Arrays

10 Copyright © 2014 by John Wiley & Sons. All rights reserved.10 Programming Question  Write a tester program called ArrayDemo. Class should declare an integer array called values of 5 elements. Assign each element the value of its index. Print all elements along with the index.  A sample run is shown: values[0] = 0 values[1] = 1 values[2] = 2 values[3] = 3 values[4] = 4 Print the values variable. What happens? Modify the program so that you have 1000 elements. As previous, each element should store value of it’s index. Try printing value at index=1000. What happens?

11 Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Answer public class ArrayDemo{ public static void main(String args[]) { final int n = 10; int values[] = new int[n]; for(int i=0; i<n;i++) { values[i] = i; } for(int i=0; i<n;i++) { System.out.printf("values[%d]=%d\n", i, values[i]); } System.out.println("values = "+values); System.out.println("values[10]="+values[10]); } ArrayDemo.java

12 Copyright © 2014 by John Wiley & Sons. All rights reserved.12 Arrays – Bounds Error  A error you just saw is called a bounds error  Bounds error occurs if you supply an invalid array index.   Causes your program to terminate with a run-time error.  Example: double[] values = new double[10]; values[10] = value; // Error, non-existing index

13 Copyright © 2014 by John Wiley & Sons. All rights reserved.13 Array Length  values.length yields the length of the values array.  There are no parentheses following length.  When iterating through elements in an already initialized array, we use this: for(int i=0; i<values.length;i++) { values[i] = i; }

14 Copyright © 2014 by John Wiley & Sons. All rights reserved.14 Declaring Arrays

15 Copyright © 2014 by John Wiley & Sons. All rights reserved.15 Array References  An array reference (i.e variable name) specifies the location of an array.  Copying the reference yields a second reference to the same array.  When you copy an array variable into another, both variables refer to the same array int[] scores = { 10, 9, 7, 4, 5 }; int[] values = scores; // Copying array reference  You can modify the array through either of the variables: scores[3] = 10; System.out.println(values[3]); // Prints 10

16 Copyright © 2014 by John Wiley & Sons. All rights reserved.16 Array References Figure 2 Two Array Variables Referencing the Same Array int[] scores = { 10, 9, 7, 4, 5 }; int[] values = scores; // Copying array reference

17 Copyright © 2014 by John Wiley & Sons. All rights reserved.17 Using Arrays with Methods  Arrays can occur as method arguments and return values.  An array as a method argument public void addScores(int[] values) { for (int i = 0; i < values.length; i++) { totalScore = totalScore + values[i]; } } To call this method int[] scores = { 10, 9, 7, 10 }; fred.addScores(scores);  A method with an array return value public int[] getScores()

18 Copyright © 2014 by John Wiley & Sons. All rights reserved.18 Partially Filled Arrays  Array length = maximum number of elements in array.  Usually, array is partially filled  Define an array larger than you will need final int LENGTH = 100; double[] values = new double[LENGTH];  How do you find out how many elements are actually in the array?

19 Copyright © 2014 by John Wiley & Sons. All rights reserved.19 Partially Filled Arrays  How do you find out how many elements are actually in the array? Use companion variable to keep track of current size: call it currentSize

20 Copyright © 2014 by John Wiley & Sons. All rights reserved.20 Partially Filled Arrays  A loop to fill the array int currentSize = 0; Scanner in = new Scanner(System.in); while (in.hasNextDouble()) { if (currentSize < values.length) { values[currentSize] = in.nextDouble(); currentSize++; } }  At the end of the loop, currentSize contains the actual number of elements in the array.  Note: Stop accepting inputs when currentSize reaches the array length.

21 Copyright © 2014 by John Wiley & Sons. All rights reserved.21 Partially Filled Arrays

22 Copyright © 2014 by John Wiley & Sons. All rights reserved.22 Partially Filled Arrays  To process the gathered array elements, use the companion variable, not the array length: for (int i = 0; i < currentSize; i++) { System.out.println(values[i]); }  With a partially filled array, you need to remember how many elements are filled.

23 Copyright © 2014 by John Wiley & Sons. All rights reserved.23 Question Answer: int[] primes = { 2, 3, 5, 7, 11 }; Declare an array of integers containing the first five prime numbers.

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24 Question Answer: 2, 3, 5, 3, 2 Assume the array primes has been initialized as described in Self Check 1. What does it contain after executing the following loop? for (int i = 0; i < 2; i++) { primes[4 - i] = primes[i]; }

25 Copyright © 2014 by John Wiley & Sons. All rights reserved.25 Question Answer: public class Lottery { public int[] getCombination(int n) {... }... }  Declare a method of a class Lottery that returns a combination of n numbers. You don’t need to implement the method.

26 Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Programming Question  Modify the class ArrayDemo to do the following:  Define a double array called rainfall of 100 elements. Initialize each element by a user keyboard input. User can any time denote that he/she is done entering numbers by inputting non-number value. i.e. user is not required to enter values for all 100 elements.  Calculate and print average rainfall.  A sample run is shown: >Enter rainfall: 20 30 45 65.8 34 A > The average rainfall is 38.96

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 Answer import java.util.Scanner; public class ArrayDemo { public static void main(String args[]) { double[] rainfall = new double[100]; Scanner in = new Scanner(System.in); int currentSize=0; do { if(currentSize < rainfall.length) { rainfall[currentSize] = in.nextDouble(); currentSize++; } }while(in.hasNextDouble()); double average = 0.0; double total = 0.0; for(int i=0;i<currentSize;i++) { total += rainfall[i]; } average = total/currentSize; System.out.printf("Average rainfall=%3.2f", average); } ArrayDemo.java

28 Copyright © 2014 by John Wiley & Sons. All rights reserved.28 Make Parallel Arrays into Arrays of Objects  Don't do this! int[] accountNumbers; double[] balances;  Don't use parallel arrays Figure 4

29 Copyright © 2014 by John Wiley & Sons. All rights reserved.29 Make Parallel Arrays into Arrays of Objects Avoid parallel arrays by changing them into arrays of objects: BankAccount[] accounts; Figure 5

30 Copyright © 2014 by John Wiley & Sons. All rights reserved.30 The Enhanced for Loop  You can use the enhanced for loop to visit all elements of an array.  E.g. Totaling the elements in an array with the enhanced for loop double[] values =...; double total = 0; for (double element : values) { total = total + element; }  The loop body is executed for each element in the array values.  Read the loop as “for each element in values”.

31 Copyright © 2014 by John Wiley & Sons. All rights reserved.31 The Enhanced for Loop  Traditional alternative: for (int i = 0; i < values.length; i++) { double element = values[i]; total = total + element; }

32 Copyright © 2014 by John Wiley & Sons. All rights reserved.32 The Enhanced for Loop  Not suitable for all array algorithms. Does not allow you to modify the contents of an array.  E.g. The following loop does not fill an array with zeros: for (double element : values) { element = 0; // ERROR: this assignment does not modify // array elements }  Use a basic for loop instead: for (int i = 0; i < values.length; i++) { values[i] = 0; // OK }

33 Copyright © 2014 by John Wiley & Sons. All rights reserved.33 The Enhanced for Loop  Use the enhanced for loop if you do not need the index values in the loop body.  The enhanced for loop is a convenient mechanism for traversing all elements in a collection.

34 Copyright © 2014 by John Wiley & Sons. All rights reserved.34 Syntax 7.2 The Enhanced for Loop

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35 Common Array Algorithm: Maximum or Minimum  Finding the maximum in an array double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } } System.out.println(“largest = ”+largest);  The loop starts at 1 because we initialize largest with values[0].  Finding the minimum: reverse the comparison.  These algorithms require that the array contain at least one element.

36 Copyright © 2014 by John Wiley & Sons. All rights reserved.36 Common Array Algorithm: Linear Search  To find the position of an element: Visit all elements until you have found a match or you have come to the end of the array  Example: Find the first element that is equal to 100 int searchedValue = 100; int pos = 0; boolean found = false; while (pos < values.length && !found) { if (values[pos] == searchedValue) { found = true; } else { pos++; } } if (found) { System.out.println("Found at position: " + pos); } else { System.out.println("Not found"); }

37 Copyright © 2014 by John Wiley & Sons. All rights reserved.37 Common Array Algorithm: Linear Search  This algorithm is called a linear search.  A linear search inspects elements in sequence until a match is found.  To search for a specific element, visit the elements and stop when you encounter the match.

38 Copyright © 2014 by John Wiley & Sons. All rights reserved.38 Common Array Algorithm: Removing an Element Problem: To remove the element with index pos from the array values with number of elements currentSize.  Unordered 1.Overwrite the element to be removed with the last element of the array. values[pos] = values[currentSize - 1]; 2.Decrement the currentSize variable. currentSize--;

39 Copyright © 2014 by John Wiley & Sons. All rights reserved.39 Common Array Algorithm: Removing an Element Figure 6 Removing an Element in an Unordered Array

40 Copyright © 2014 by John Wiley & Sons. All rights reserved.40 Common Array Algorithm: Removing an Element  Ordered array 1.Move all elements following the element to be removed to a lower index. for (int i = pos + 1; i < currentSize; i++) { values[i - 1] = values[i]; } 2.Decrement the variable holding the size of the array. currentSize--;

41 Copyright © 2014 by John Wiley & Sons. All rights reserved.41 Common Array Algorithm: Removing an Element Figure 7 Removing an Element in an Ordered Array

42 Copyright © 2014 by John Wiley & Sons. All rights reserved.42 Common Array Algorithm: Inserting an Element  If order does not matter 1.Insert the new element at the end of the array. 2.Increment the variable tracking the size of the array. if (currentSize < values.length) { currentSize++; values[currentSize -1 ] = newElement; }

43 Copyright © 2014 by John Wiley & Sons. All rights reserved.43 Common Array Algorithm: Inserting an Element Figure 8 Inserting an Element in an Unordered Array

44 Copyright © 2014 by John Wiley & Sons. All rights reserved.44 Common Array Algorithm: Inserting an Element  If order matters : Increment the variable tracking the size of the array. 1.Move all elements after the insertion location to a higher index. 2.Insert the element. if (currentSize < values.length) { currentSize++; for (int i = currentSize - 1; i > pos; i--) { values[i] = values[i - 1]; } values[pos] = newElement; }

45 Copyright © 2014 by John Wiley & Sons. All rights reserved.45 Common Array Algorithm: Inserting an Element Figure 9 Inserting an Element in an Ordered Array

46 Copyright © 2014 by John Wiley & Sons. All rights reserved.46 Common Array Algorithm: Swapping Elements  To swap two elements, you need a temporary variable.  We need to save the first value in the temporary variable before replacing it. double temp = values[i]; values[i] = values[j];  Now we can set values[j] to the saved value. values[j] = temp;

47 Copyright © 2014 by John Wiley & Sons. All rights reserved.47 Common Array Algorithm: Swapping Elements Figure 10 Swapping Array Elements

48 Copyright © 2014 by John Wiley & Sons. All rights reserved.48 Common Array Algorithm: Copying an Array  Copying an array variable yields a second reference to the same array: double[] values = new double[6];... // Fill array double[] prices = values;  To make a true copy of an array, call the Arrays.copyOf method: double[] prices = Arrays.copyOf(values, values.length);

49 Copyright © 2014 by John Wiley & Sons. All rights reserved.49 Common Array Algorithm: Copying an Array Figure 11 Copying an Array Reference versus Copying an Array

50 Copyright © 2014 by John Wiley & Sons. All rights reserved.50 Common Array Algorithm: Growing an Array  To grow an array that has run out of space, use the Arrays.copyOf method to double the length of an array double[] newValues = Arrays.copyOf(values, 2 * values.length); values = newValues;

51 Copyright © 2014 by John Wiley & Sons. All rights reserved.51 Common Array Algorithm: Growing an Array Figure 12 Growing an Array

52 Copyright © 2014 by John Wiley & Sons. All rights reserved.52 Reading Input  To read a sequence of arbitrary length: Add the inputs to an array until the end of the input has been reached. Grow when needed. double[] inputs = new double[INITIAL_SIZE]; int currentSize = 0; while (in.hasNextDouble()) { // Grow the array if it has been completely filled if (currentSize >= inputs.length) { inputs = Arrays.copyOf(inputs, 2 * inputs.length); // Grow the inputs array } inputs[currentSize] = in.nextDouble(); currentSize++; } Discard unfilled elements. inputs = Arrays.copyOf(inputs, currentSize);

53 Copyright © 2014 by John Wiley & Sons. All rights reserved.53 Programming Question  Modify ArrayDemo class to find the largest value in values array, mark and print the largest.  A sample run is shown: Program Run Please enter values, Q to quit: 34.5 80 115 44.5 Q 34.5 80 115 <== largest value 44.5

54 Copyright © 2014 by John Wiley & Sons. All rights reserved.54 Answer 1 import java.util.Scanner; 2 3 /** 4 This program reads a sequence of values and prints them, marking the largest value. 5 */ 6 public class ArrayDemo 7 { 8 public static void main(String[] args) 9 { 10 final int LENGTH = 100; 11 double[] values = new double[LENGTH]; 12 int currentSize = 0; 13 14 // Read inputs 15 16 System.out.println("Please enter values, Q to quit:"); 17 Scanner in = new Scanner(System.in); 18 while (in.hasNextDouble() && currentSize < values.length) 19 { 20 values[currentSize] = in.nextDouble(); 21 currentSize++; 22 } 23 Continued ArrayDemo.java

55 Copyright © 2014 by John Wiley & Sons. All rights reserved.55 24 // Find the largest value 25 26 double largest = values[0]; 27 for (int i = 1; i < currentSize; i++) 28 { 29 if (values[i] > largest) 30 { 31 largest = values[i]; 32 } 33 } 34 35 // Print all values, marking the largest 36 37 for (int i = 0; i < currentSize; i++) 38 { 39 System.out.print(values[i]); 40 if (values[i] == largest) 41 { 42 System.out.print(" <== largest value"); 43 } 44 System.out.println(); 45 } 46 } 47 } Continued

56 Copyright © 2014 by John Wiley & Sons. All rights reserved.56 Question Consider the algorithm to find the largest element in an array. Why don’t we initialize largest and i with zero, like this? double largest = 0; for (int i = 0; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } double largest = values[0]; for (int i = 1; i < currentSize; i++){ if (values[i] > largest){ largest = values[i]; } Original code:

57 Copyright © 2014 by John Wiley & Sons. All rights reserved.57 Answer If all elements of values are negative, then the result is incorrectly computed as 0.

58 Copyright © 2014 by John Wiley & Sons. All rights reserved.58 Question When finding the position of a match, we used a while loop, not a for loop. What is wrong with using this loop instead? for (pos = 0, found = false; pos < values.length && !found; pos++) { if (values[pos] == 100) { found = true; } } int searchedValue = 100; int pos = 0; boolean found = false; while (pos < values.length && !found) { if (values[pos] == searchedValue) { found = true; } else { pos++; } } if (found) { System.out.println("Found at position: " + pos); } else { System.out.println("Not found"); } Original code:

59 Copyright © 2014 by John Wiley & Sons. All rights reserved.59 Answer If there is a match, then pos is incremented before the loop exits.

60 Copyright © 2014 by John Wiley & Sons. All rights reserved.60 Question When inserting an element into an array, we moved the elements with larger index values, starting at the end of the array. Why is it wrong to start at the insertion location, like this? for (int i = pos; i < currentSize - 1; i++) { values[i + 1] = values[i]; } for (int i = pos + 1; i < currentSize; i++) { values[i - 1] = values[i]; } Original code:

61 Copyright © 2014 by John Wiley & Sons. All rights reserved.61 Answer This loop sets all elements to values[pos].

62 Copyright © 2014 by John Wiley & Sons. All rights reserved.62 Two-Dimensional Arrays  An arrangement consisting of rows and columns of values Also called a matrix.  Example: medal counts of the figure skating competitions at the 2010 Winter Olympics. Figure 13 Figure Skating Medal counts

63 Copyright © 2014 by John Wiley & Sons. All rights reserved.63 Two-Dimensional Arrays  Use a two-dimensional array to store tabular data.  When constructing a two-dimensional array, specify how many rows and columns are needed: final int COUNTRIES = 7; //number of rows (dimension 1) final int MEDALS = 3; //number of columns (dimension 2) int[][] counts = new int[COUNTRIES][MEDALS];  2-d array of 7 rows and 3 columns OR  7 arrays each having 3 elements (array of arrays) rows columns

64 Copyright © 2014 by John Wiley & Sons. All rights reserved.64 Two-Dimensional Arrays  int[][] counts = new int[COUNTRIES][MEDALS]; counts memory Each row is a 1-d array

65 Copyright © 2014 by John Wiley & Sons. All rights reserved.65 Two-Dimensional Arrays  Method1:  You can declare and initialize the array by grouping each row: int[][] counts = { { 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 1, 1, 0 } };  You cannot change the size of a two-dimensional array once it has been declared.

66 Copyright © 2014 by John Wiley & Sons. All rights reserved.66 Two-Dimensional Arrays  Method2:  Assign values to individual elements:  E.g. counts[0][2]=1

67 Copyright © 2014 by John Wiley & Sons. All rights reserved.67 Syntax 7.3 Two-Dimensional Array Declaration

68 Copyright © 2014 by John Wiley & Sons. All rights reserved.68 Accessing Elements  Access by using two index values, array[i][j] int medalCount = counts[3][1];  Use nested loops to access all elements in a two- dimensional array.

69 Copyright © 2014 by John Wiley & Sons. All rights reserved.69 Accessing Elements Figure 14 Accessing an Element in a Two-Dimensional Array

70 Copyright © 2014 by John Wiley & Sons. All rights reserved.70 Programming Question  Modify ArrayDemo class to declare and initialize the counts array and then print the values in the array in a tabular format. Hint: for printing the row and column headers, define two separate arrays Number of rows: counts.length Number of columns: counts[0].length  A sample program run is shown below:

71 Copyright © 2014 by John Wiley & Sons. All rights reserved.71  Start by copying the following code to ArrayDemo.java: int[][] counts = { { 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 1, 1, 0 } }; //iniialize headers String[] columnHeader = {"Country", "Gold", "Silver", "Bronze"}; String[] rowHeader = {"Canada", "China", "Germany", "Korea", "Japan", "Russia", "United States"}; //TODO:print array in tabular format

72 Copyright © 2014 by John Wiley & Sons. All rights reserved.72 Answer public class ArrayDemo{ public static void main(String args[]){ int[][] counts = {{ 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 } }; //iniialize headers String[] columnHeader = {"Country", "Gold", "Silver", "Bronze"}; String[] rowHeader = {"Canada","China","Germany","Korea","Japan","Russia","United States"}; //print column headers for(int i = 0; i < columnHeader.length; i++)//for each column { System.out.printf("%15s",columnHeader[i]); //print column header } System.out.println(); //print array in tabular format for (int i = 0; i < counts.length; i++) //for each row { //print row header System.out.printf("%15s",rowHeader[i]); for (int j = 0; j < counts[0].length; j++)//for each element in row i { System.out.printf("%15d", counts[i][j]); //print element } System.out.println(); } ArrayDemo.java

73 Copyright © 2014 by John Wiley & Sons. All rights reserved.73 Accessing Elements  Number of rows: counts.length  Number of columns: counts[0].length  Example: print all the elements of the counts array for (int i = 0; i < counts.length; i++) //for each row { for (int j = 0; j < counts[0].length; j++) //for each element/column in row { System.out.printf("%8d", counts[i][j]); } System.out.println(); }

74 Copyright © 2014 by John Wiley & Sons. All rights reserved.74 Locating Neighboring Elements Figure 15 Neighboring Locations in a Two-Dimensional Array  Watch out for elements at the boundary array counts[0][1] does not have a neighbor to the top

75 Copyright © 2014 by John Wiley & Sons. All rights reserved.75 Programming Question  Modify ArraysDemo.java to print a new column with the total number of medals won by each country Hint: This is same as sum of each row  A sample run is shown below:

76 Copyright © 2014 by John Wiley & Sons. All rights reserved.76 Accessing Rows and Columns  Problem: To find the number of medals won by a country Find the sum of the elements in a row  To find the sum of the i th row compute the sum of counts[i][j], where j ranges from 0 to MEDALS - 1.

77 Copyright © 2014 by John Wiley & Sons. All rights reserved.77 1 /** 2 This program prints a table of medal winner counts with row totals. 3 */ 4 public class ArrayDemo 5 { 6 public static void main(String[] args) 7 { 8 final int COUNTRIES = 7; 9 final int MEDALS = 3; 10 11 String[] countries = 12 { 13 "Canada", 14 "China", 15 "Germany", 16 "Korea", 17 "Japan", 18 "Russia", 19 "United States" 20 }; 21 22 int[][] counts = 23 { 24 { 1, 0, 1 }, 25 { 1, 1, 0 }, 26 { 0, 0, 1 }, 27 { 1, 0, 0 }, 28 { 0, 1, 1 }, 29 { 0, 1, 1 }, 30 { 1, 1, 0 } 31 }; 32 Continued ArrayDemo.java

78 Copyright © 2014 by John Wiley & Sons. All rights reserved.78 33 System.out.println(" Country Gold Silver Bronze Total"); 34 35 // Print countries, counts, and row totals 36 for (int i = 0; i < COUNTRIES; i++) 37 { 38 // Process the ith row 39 System.out.printf("%15s", countries[i]); 40 41 int total = 0; 42 43 // Print each row element and update the row total 44 for (int j = 0; j < MEDALS; j++) 45 { 46 System.out.printf("%8d", counts[i][j]); 47 total = total + counts[i][j]; 48 } 49 50 // Display the row total and print a new line 51 System.out.printf("%8d\n", total); 52 } 53 } 54 }

79 Copyright © 2014 by John Wiley & Sons. All rights reserved.79 Accessing Rows and Columns  To find the sum of the j th column Form the sum of counts[i][j], where i ranges from 0 to COUNTRIES – 1 int total = 0; for (int i = 0; i < COUNTRIES; i++ { total = total + counts[i][j]; }

80 Copyright © 2014 by John Wiley & Sons. All rights reserved.80 Question Consider an 8 × 8 array for a board game: int[][] board = new int[8][8]; Using two nested loops, initialize the board so that zeros and ones alternate, as on a checkerboard: 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1... 1 0 1 0 1 0 1 0 Hint: Check whether i + j is even.

81 Copyright © 2014 by John Wiley & Sons. All rights reserved.81 Answer for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { board[i][j] = (i + j) % 2; } }

82 Copyright © 2014 by John Wiley & Sons. All rights reserved.82 Array Lists  An array list stores a sequence of values whose size can change.  An array list can grow and shrink as needed.  ArrayList class supplies methods for many common tasks, such as inserting and removing elements.  An array list expands to hold as many elements as needed.

83 Copyright © 2014 by John Wiley & Sons. All rights reserved.83 Syntax 7.4 Array Lists

84 Copyright © 2014 by John Wiley & Sons. All rights reserved.84 Declaring and Using Array Lists  To declare an array list of strings ArrayList names = new ArrayList ();  To use an array list import java.util.ArrayList;  Angle brackets denote a type parameter Replace String with any other class to get a different array list type

85 Copyright © 2014 by John Wiley & Sons. All rights reserved.85 Declaring and Using Array Lists  ArrayList is first constructed, it has size 0  Use the add method to add an object to the end of the array list: names.add("Emily"); // Now names has size 1 and element "Emily” names.add("Bob"); // Now names has size 2 and elements "Emily", "Bob” names.add("Cindy"); // names has size 3 and elements "Emily", "Bob", // and "Cindy”  The size method gives the current size of the array list. Size is now 3 Figure 17 Adding an Array List Element with add

86 Copyright © 2014 by John Wiley & Sons. All rights reserved.86 Declaring and Using Array Lists  To obtain an array list element, use the get method Index starts at 0  To retrieve the name with index 2: String name = names.get(2); // Gets the third element // of the array list  The last valid index is names.size() - 1 A common bounds error: int i = names.size(); name = names.get(i); // Error  To set an array list element to a new value, use the set method: names.set(2, "Carolyn");

87 Copyright © 2014 by John Wiley & Sons. All rights reserved.87 Declaring and Using Array Lists  An array list has methods for adding and removing elements in the middle.  This statement adds a new element at position 1 and moves all elements with index 1 or larger by one position. names.add(1, "Ann");

88 Copyright © 2014 by John Wiley & Sons. All rights reserved.88 Declaring and Using Array Lists Figure 18 Adding and Removing Elements in the Middle of an Array List

89 Copyright © 2014 by John Wiley & Sons. All rights reserved.89 Declaring and Using Array Lists  The remove method, removes the element at a given position moves all elements after the removed element down by one position and reduces the size of the array list by 1. names.remove(1);

90 Copyright © 2014 by John Wiley & Sons. All rights reserved.90 Programming Question  Write a tester class ArrayListDemo to display the words of a file (words.txt) as a list: 1.Read file content to an arrayList allWords Hint: Use Scanner class Scanner input = new Scanner(new File("words.txt")); 2.Print elements in allWords 3.Print elements in allWords in reverse order A sample run is sown below: It is a beautiful day words.txt public class ArrayListDemo{ public static void main(String args[]) throws Exception { //your code goes ere } ArrayListDemo.java

91 Copyright © 2014 by John Wiley & Sons. All rights reserved.91 Answer import java.util.ArrayList; import java.util.Scanner; import java.io.File; public class ArrayListDemo { public static void main(String args[])throws Exception { //populate allwords ArrayList allWords = new ArrayList (); Scanner input = new Scanner(new File("words.txt")); while (input.hasNext()) { String word = input.next(); allWords.add(word); } //print allwords System.out.println(allWords); //print in reverse order for(int i=allWords.size()-1; i>=0;i--) { System.out.print(allWords.get(i)+","); } }

92 Copyright © 2014 by John Wiley & Sons. All rights reserved.92 Declaring and Using Array Lists  To print an array list: System.out.println(names); // Prints [Emily, Bob, Carolyn]

93 Copyright © 2014 by John Wiley & Sons. All rights reserved.93 Using the Enhanced for Loop with Array Lists  You can use the enhanced for loop to visit all the elements of an array list ArrayList names =... ; for (String name : names) { System.out.println(name); }  This is equivalent to: for (int i = 0; i < names.size(); i++) { String name = names.get(i); System.out.println(name); }

94 Copyright © 2014 by John Wiley & Sons. All rights reserved.94 Copying Array Lists  Copying an array list reference yields two references to the same array list.  After the code below is executed Both names and friends reference the same array list to which the string "Harry" was added. ArrayList friends = names; friends.add("Harry"); Figure 19 Copying an Array List Reference

95 Copyright © 2014 by John Wiley & Sons. All rights reserved.95 Copying Array Lists  To make a copy of an array list, construct the copy and pass the original list into the constructor: ArrayList newNames = new ArrayList (names);  Deep copy vs shallow copy

96 Copyright © 2014 by John Wiley & Sons. All rights reserved.96 Working With Array Lists

97 Copyright © 2014 by John Wiley & Sons. All rights reserved.97 Wrapper Classes  You cannot directly insert primitive type values into array lists.  Like truffles that must be in a wrapper to be sold, a number must be placed in a wrapper to be stored in an array list.  Use the matching wrapper class.

98 Copyright © 2014 by John Wiley & Sons. All rights reserved.98 Wrapper Classes  To collect double values in an array list, you use an ArrayList.  Auto-boxing: Automatic conversion between primitive types and the corresponding wrapper classes: Double wrapper = 29.95; Wrapper values are automatically “unboxed” to primitive types double x = wrapper; Figure 20 A Wrapper Class Variable

99 Copyright © 2014 by John Wiley & Sons. All rights reserved.99 Storing Input Values in an Array List  To collect an unknown number of inputs, array lists are much easier to use than arrays.  Simply read the inputs and add them to an array list: ArrayList inputs = new ArrayList (); while (in.hasNextDouble()) { inputs.add(in.nextDouble()); }

100 Copyright © 2014 by John Wiley & Sons. All rights reserved.100 Removing Matches  To remove elements from an array list, call the remove method.  Error: skips the element after the moved element ArrayList words =...; for (int i = 0; i < words.size(); i++) { String word = words.get(i); if (word.length() < 4) { //Remove the element at index i. } }

101 Copyright © 2014 by John Wiley & Sons. All rights reserved.101 Removing Matches  Should not increment i when an element is removed  Pseudocode If the element at index i matches the condition Remove the element. Else Increment i.

102 Copyright © 2014 by John Wiley & Sons. All rights reserved.102 Removing Matches  Use a while loop, not a for loop int i = 0; while (i < words.size()) { String word = words.get(i); if (word.length() < 4) { words.remove(i); } else { i++; } }

103 Copyright © 2014 by John Wiley & Sons. All rights reserved.103 Choosing Between Array Lists and Arrays  For most programming tasks, array lists are easier to use than arrays Array lists can grow and shrink. Arrays have a nicer syntax.  Recommendations If the size of a collection never changes, use an array. If you collect a long sequence of primitive type values and you are concerned about efficiency, use an array. Otherwise, use an array list.

104 Copyright © 2014 by John Wiley & Sons. All rights reserved.104 Choosing Between Array Lists and Arrays

105 Copyright © 2014 by John Wiley & Sons. All rights reserved.105 Programming Question  Modify ArrayListDemo class to use an ArrayList instead of an array (called values) to maintain the user input. Write code that find and print the largest in the values array list.  A sample program run is shown: Please enter values, Q to quit: 35 80 115 44.5 Q 35 80 115 <== largest value 44.5

106 Copyright © 2014 by John Wiley & Sons. All rights reserved.106 Answer 1 import java.util.ArrayList; 2 import java.util.Scanner; 3 4 /** 5 This program reads a sequence of values and prints them, marking the largest value. 6 */ 7 public class ArrayListDemo 8 { 9 public static void main(String[] args) 10 { 11 ArrayList values = new ArrayList (); 12 13 // Read inputs 14 15 System.out.println("Please enter values, Q to quit:"); 16 Scanner in = new Scanner(System.in); 17 while (in.hasNextDouble()) 18 { 19 values.add(in.nextDouble()); 20 } 21 Continued ArrayListDemo.java

107 Copyright © 2014 by John Wiley & Sons. All rights reserved.107 22 // Find the largest value 23 24 double largest = values.get(0); 25 for (int i = 1; i < values.size(); i++) 26 { 27 if (values.get(i) > largest) 28 { 29 largest = values.get(i); 30 } 31 } 32 33 // Print all values, marking the largest 34 35 for (double element : values) 36 { 37 System.out.print(element); 38 if (element == largest) 39 { 40 System.out.print(" <== largest value"); 41 } 42 System.out.println(); 43 } 44 } 45 }

108 Copyright © 2014 by John Wiley & Sons. All rights reserved.108 Question Answer: ArrayList primes = new ArrayList (); primes.add(2); primes.add(3); primes.add(5); primes.add(7); primes.add(11); Declare an array list primes of integers that contains the first five prime numbers (2, 3, 5, 7, and 11).

109 Copyright © 2014 by John Wiley & Sons. All rights reserved.109 Question Answer: for (int i = primes.size() - 1; i >= 0; i--) { System.out.println(primes.get(i)); } Given the array list primes declared in previous slide, write a loop to print its elements in reverse order, starting with the last element.

110 Copyright © 2014 by John Wiley & Sons. All rights reserved.110 Answer Answer: "Ann", "Cal" What does the array list names contain after the following statements? ArrayList names = new ArrayList ; names.add("Bob"); names.add(0, "Ann"); names.remove(1); names.add("Cal");

111 Copyright © 2014 by John Wiley & Sons. All rights reserved.111 Question Consider this method that appends the elements of one array list to another: public void append(ArrayList target,ArrayList source) { for (int i = 0; i < source.size(); i++) { target.add(source.get(i)); } What are the contents of names1 and names2 after these statements? ArrayList names1 = new ArrayList (); names1.add("Emily"); names1.add("Bob"); names1.add("Cindy"); ArrayList names2 = new ArrayList (); names2.add("Dave"); append(names1, names2); Continued

112 Copyright © 2014 by John Wiley & Sons. All rights reserved.112 Answer names1 contains "Emily", "Bob", "Cindy", "Dave"; names2 contains "Dave"

113 Copyright © 2014 by John Wiley & Sons. All rights reserved.113 Question Answer: Because the number of weekdays doesn’t change, there is no disadvantage to using an array, and it is easier to initialize: String[] weekdayNames = { "Monday", "Tuesday", "Wednesday", "Thursday", “Friday”, "Saturday", "Sunday" }; Suppose you want to store the names of the weekdays. Should you use an array list or an array of seven strings?

114 Copyright © 2014 by John Wiley & Sons. All rights reserved.114 Regression Testing  Type of software testing that seeks to uncover new software bugs, or regressions  Test suite: a set of tests for repeated testing Rerun previously completed tests Checking whether program behavior has changed and whether previously fixed faults have re-emerged.

115 Copyright © 2014 by John Wiley & Sons. All rights reserved.115 Regression Testing – Two Approaches  Organize a suite of test with multiple tester classes: ScoreTester1, ScoreTester2, … public class ScoreTester1 { public static void main(String[] args) { Student fred = new Student(100); fred.addScore(10); fred.addScore(20); fred.addScore(5); System.out.println("Final score: " + fred.finalScore()); System.out.println("Expected: 30"); } }  Provide a generic tester, and feed it inputs from multiple files.

116 Copyright © 2014 by John Wiley & Sons. All rights reserved.116 section_8/ScoreTester.javaScoreTester.java generic tester 1 import java.util.Scanner; 2 3 public class ScoreTester 4 { 5 public static void main(String[] args) 6 { 7 Scanner in = new Scanner(System.in); 8 double expected = in.nextDouble(); 9 Student fred = new Student(100); 10 while (in.hasNextDouble()) 11 { 12 if (!fred.addScore(in.nextDouble())) 13 { 14 System.out.println("Too many scores."); 15 return; 16 } 17 } 18 System.out.println("Final score: " + fred.finalScore()); 19 System.out.println("Expected: " + expected); 20 } 21 }

117 Copyright © 2014 by John Wiley & Sons. All rights reserved.117 Input and Output Redirection  Section_8/input1.txt contains: 30 10 20 5  Type the following command into a shell window Input redirection java ScoreTester < input1.txt  Program Run: Final score: 30 Expected: 30  Output redirection: java ScoreTester output1.txt


Download ppt "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 7 – Arrays and Array Lists."

Similar presentations


Ads by Google