Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 10 How to work with arrays Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 1 Objectives Applied Given a list of values or objects, write code that creates a onedimensional array that stores those values or objects. Use for loops and enhanced for loops to work with the values or objects in an array. Use the methods of the Arrays class to fill an array, compare two arrays, sort an array, or search an array for a value. Implement the Comparable interface in any class you create. Create a reference to an array and copy elements from one array to another. Given a table of values or objects, write code that creates a twodimensional array that stores those values or objects. The array can be either rectangular or jagged. Use for loops and enhanced for loops to work with the values or objects in a two-dimensional array. Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 2 Objectives (continued) Given the Java code for an application that uses any of the language elements presented in this chapter, explain what each statement in the application does. Knowledge In general, explain what an array is and how you work with it. Describe the operation of the enhanced for loop and explain why it’s especially useful with arrays. Explain when you need to implement the Comparable interface in a class you create. Explain what happens when you assign a new array to an existing array variable. Describe the difference between a rectangular array and a jagged array, and explain the difference in how you create them. Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 3 The syntax for declaring and instantiating an array Two ways to declare an array type[] arrayName; type arrayName[]; How to instantiate an array arrayName = new type[length]; How to declare and instantiate an array in one statement type[] arrayName = new type[length]; Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 4 Examples of array declarations Code that declares an array of doubles double[] prices; Code that instantiates an array of doubles prices = new double[4]; Code that declares and instantiates an array of doubles in one statement double[] prices = new double[4]; Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 5 Other examples of array declarations An array of String objects String[] titles = new String[3]; An array of Product objects Product[] products = new Product[5]; Code that uses a constant to specify the array length final int TITLE_COUNT = 100; // array size set at // compile time String[] titles = new String[TITLE_COUNT]; Code that uses a variable to specify the array length int titleCount = 100; // array size not set // until run time String[] titles = new String[titleCount]; Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 6 How to create an array An array can store more than one primitive type or object. An element is one of the items in an array. To create an array, you must declare a variable of the correct type and instantiate an array object that the variable refers to. To declare an array variable, you code a set of empty brackets after the type or the variable name. To instantiate an array, you use the new keyword and specify the length, or size, of the array in brackets following the array type. You can specify the array length by coding a literal value or by using a constant or variable of type int. When you instantiate an array of primitive types, numeric types are set to zeros and boolean types to false. When you create an array of objects, they are set to nulls. Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 7 The syntax for referring to an element of an array arrayName[index] The syntax for creating an array and assigning values in one statement type[] arrayName = {value1, value2, value3, ...}; How to assign values to the elements of an array To refer to the elements, you use an index that ranges from zero (the first element in the array) to one less than the total number of elements. If you specify an index that’s less than zero or greater than the upper bound of the array, an ArrayIndexOutOfBoundsException will be thrown. You can instantiate an array and provide initial values in a single statement by listing the values in braces. The number of values determines the size of the array. Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 8 Code that accesses each element to assign… …values to an array of double types double[] prices = new double[4]; prices[0] = 14.95; prices[1] = 12.95; prices[2] = 11.95; prices[3] = 9.95; //prices[4] = 8.95; // this would throw an // ArrayIndexOutOfBoundsException …values to an array of String types String[] names[0] names[1] names[2] names = new String[3]; = "Ted Lewis"; = "Sue Jones"; = "Ray Thomas"; …objects to an array of Product objects Product[] products = new Product[2]; products[0] = new Product("java"); products[1] = new Product("jsps"); Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 9 Examples that create arrays and assign values in one statement double[] prices = {14.95, 12.95, 11.95, 9.95}; String[] names = {"Ted Lewis", "Sue Jones", "Ray Thomas"}; Product[] products = {new Product("java"), new Product("jsps")}; Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 10 The syntax for getting the length of an array arrayName.length Code that puts the numbers 0 through 9 in an array int[] values = new int[10]; for (int i = 0; i < values.length; i++) { values[i] = i; } How to use for loops with arrays You can use the length field of an array to determine how many elements are defined for the array. For loops are often used to process each element in an array. Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 11 Code that prints an array of prices to the console double[] prices = {14.95, 12.95, 11.95, 9.95}; for (int i = 0; i < prices.length; i++) { System.out.println(prices[i]); } The console output 14.95 12.95 11.95 9.95 Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 12 Code that computes the average of the array of prices double sum = 0.0; for (int i = 0; i < prices.length; i++) { sum += prices[i]; } double average = sum/prices.length; Another way to compute the average in a for loop double sum = 0.0; for (int i = 0; i < prices.length; sum += prices[i++]); average = sum/prices.length; Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 13 The syntax of the enhanced for loop for (type variableName : arrayName) { statements } How to use enhanced for loops with arrays Java 5.0 provides a new form of the for loop called an enhanced for loop. The enhanced for loop is sometimes called a foreach loop because it lets you process each element of an array. Within the parentheses of an enhanced for loop, you declare a variable with the same type as the array followed by a colon and the name of the array. With each iteration of the loop, the variable that’s declared by the for loop is assigned the value of the next element in the array. Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 14 Code that prints an array of prices to the console double[] prices = {14.95, 12.95, 11.95, 9.95}; for (double price : prices) { System.out.println(price); } The console output 14.95 12.95 11.95 9.95 Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 15 Code that computes the average of the array of prices double sum = 0.0; for (double price : prices) { sum += price; } double average = sum/prices.length; Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 16 The Arrays class java.util.Arrays Static methods of the Arrays class Method fill(arrayName, value) fill(arrayName, index1, index2, value) equals(arrayName1, arrayName2) Murach’s Beg. Java 2, JDK 5, C10 Description Fills all elements of the array with the specified value. Fills elements of the array with the specified value from the index1 element to, but not including, the index2 element. Returns a boolean true value if both arrays are of the same type and all of the elements are equal to each other. © 2005, Mike Murach & Associates, Inc. Slide 17 Static methods of the Arrays class (continued) Method Sort(arrayName) sort(arrayName, index1, index2) binarySearch( arrayName, value) Murach’s Beg. Java 2, JDK 5, C10 Description Sorts the elements into ascending order. Sorts the elements into ascending order from the index1 element to, but not including, the index2 element. Returns an int value for the index of the specified value in the specified array; returns a negative number if the specified value is not found. Array must first be sorted by the sort method. © 2005, Mike Murach & Associates, Inc. Slide 18 The methods of the Arrays class All of these methods accept arrays of primitive data types and arrays of objects for the arrayName argument. The methods all accept primitive types and objects for the value argument. All of the index arguments must be int types. If an index argument is less than zero or greater than one less than the length of the array, the method will throw an ArrayIndexOutOfBoundsException. If you use the sort method on an array of objects created from a user-defined class, the class must implement the Comparable interface. Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 19 Code that uses the fill method int[] quantities = new int[5]; Arrays.fill(quantities, 1); // all elements are set to 1 Code that uses the fill method to fill 3 elements in an array int[] quantities = new int[5]; Arrays.fill(quantities, 1, 4, 100); // elements 1, 2, and 3 are set to 100 Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 20 Code that uses the equals method String[] titles1 = {"War and Peace", "Gone With the Wind"}; String[] titles2 = {"War and Peace", "Gone With the Wind"}; if (titles1 == titles2) System.out.println("titles1 == titles2 is true"); else System.out.println("titles1 == titles2 is false"); if (Arrays.equals(titles1, titles2)) System.out.println("Arrays.equals(titles1, titles2) is true"); else System.out.println("Arrays.equals(titles1, titles2) is false"); The console output titles1 == titles2 is false Arrays.equals(titles1, titles2) is true Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 21 Code that uses the sort method int[] numbers = {2,6,4,1,8,5,9,3,7,0}; Arrays.sort(numbers); for (int num : numbers) { System.out.print(num + " "); } The console output 0 1 2 3 4 5 6 7 8 9 Code that uses the sort and binarySearch methods String[] productCodes = {"mcbl", "jsps", "java"}; Arrays.sort(productCodes); int index = Arrays.binarySearch(productCodes, "mcbl"); // sets index to 2 Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 22 The Comparable interface defined in the Java API public interface Comparable { int compareTo(Object obj); } How to implement the Comparable interface Define the compareTo method. Then, the sort method of the Arrays class uses the compareTo method to sort an array of objects created from that class. The compareTo method must return -1 if the current object is less than the passed object, 0 if the objects are equal, and 1 if the current object is greater than the passed object. Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 23 An Item class that implements the Comparable interface public class Item implements Comparable { private int number; private String description; public Item(int number, String description) { this.number = number; this.description = description; } public int getNumber() { return number; } public String getDescription() { return description; } Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 24 An Item class that implements the Comparable interface (continued) public int compareTo(Object o) { Item i = (Item) o; if (this.getNumber() < i.getNumber()) return -1; if (this.getNumber() > i.getNumber()) return 1; return 0; } } Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 25 Code that sorts an array of Item objects Item[] items = new Item[3]; items[0] = new Item(102, "Duct Tape"); items[1] = new Item(103, "Bailing Wire"); items[2] = new Item(101, "Chewing Gum"); Arrays.sort(items); for (Item i : items) System.out.println(i.getNumber() + ": " + i.getDescription()); The console output 101: Chewing Gum 102: Duct Tape 103: Bailing Wire Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 26 How to create a reference to an array Example 1: Code that creates a reference to an array double[] grades = {92.3, 88.0, 95.2, 90.5}; double[] percentages = grades; percentages[1] = 70.2; // changes grades[1] too System.out.println("grades[1]=" + grades[1]); // prints 70.2 Example 2: Code that reuses an array variable double[] grades = new grades[5]; grades = new grades[20] Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 27 How to copy elements of one array to another The syntax of the arraycopy method of the System class System.arraycopy(fromArray, intFromIndex, toArray, intToIndex, intLength); Example 1: Code that copies the values of an array double[] grades = {92.3, 88.0, 95.2, 90.5}; double[] percentages = new double[grades.length]; System.arraycopy(grades, 0, percentages, 0, grades.length); percentages[1] = 70.2; // doesn't change grades[1] System.out.println("grades[1]=" + grades[1]); // prints 88.0 Example 2: Code that copies part of one array to another double[] grades = {92.3, 88.0, 95.2, 90.5}; Arrays.sort(grades); double[] lowestGrades = new double[2]; System.arraycopy(grades, 0, lowestGrades, 0, 2); double[] highestGrades = new double[2]; System.arraycopy(grades, 2, highestGrades, 0, 2); Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 28 How to refer to and copy arrays To create a reference to an existing array, code an assignment statement that assigns an array variable to the existing array. Then, two variables will point to the same array in memory. To copy the values of one array into another, use the arraycopy method of the System class. When you copy an array, the target array must be the same type as the sending array and it must be large enough to receive all of the elements that are copied to it. Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 29 How to work with rectangular arrays Two-dimensional arrays use two indexes and allow data to be stored in a table that consists of rows and columns. This can also be thought of as an array of arrays where each row is a separate array of columns. A rectangular array is a two-dimensional array whose rows all have the same number of columns. How to create a rectangular array The syntax for creating a rectangular array type[][] arrayName = new type[rowCount][columnCount]; A statement that creates a 3x2 array int[][] numbers = new int[3][2]; Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 30 How to assign values to a rectangular array The syntax for referring to an element of a rectangular array arrayName[rowIndex][columnIndex] The indexes for a 3x2 array [0][0] [1][0] [2][0] [0][1] [1][1] [2][1] Code that assigns values to the array numbers[0][0] numbers[0][1] numbers[1][0] numbers[1][1] numbers[2][0] numbers[2][1] = = = = = = 1; 2; 3; 4; 5; 6; Code that creates a 3x2 array and initializes it in one statement int[][] numbers = { {1,2} {3,4} {5,6} }; Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 31 Code that processes a rectangular array with nested for loops int[][] numbers = { {1,2}, {3,4}, {5,6} }; for (int i = 0; i < numbers.length; i++) { for (int j = 0; j < numbers[i].length; j++) System.out.print(numbers[i][j] + " "); System.out.print("\n"); } The console output 1 3 5 2 4 6 Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 32 The syntax for creating a jagged array type[][] arrayName = new type[rowCount][]; How to work with jagged arrays A jagged array is a two-dimensional array whose rows have different numbers of columns. When you create a jagged array, you specify the number of rows in the array, but you leave the size of each column array unspecified and set it later. Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 33 Code that creates a jagged array of integers int[][] numbers = new int[3][]; numbers[0] = new int[10]; numbers[1] = new int[15]; numbers[2] = new int[20]; Code that creates and initializes a jagged array of strings String[][] titles = {{"War and Peace", "Wuthering Heights", "1984"}, {"Casablanca", "Wizard of Oz", "Star Wars", "Birdy"}, {"Blue Suede Shoes", "Yellow Submarine"}}; Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 34 Code that creates and initializes a jagged array of integers int number = 0; int[][] pyramid = new int[4][]; for (int i = 0; i < pyramid.length; i++) { pyramid[i] = new int[i+1]; for (int j = 0; j < pyramid[i].length; j++) pyramid[i][j] = number++; } Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 35 Code that prints the contents of the jagged array of integers for (int i = 0; i < pyramid.length; i++) { for (int j = 0; j < pyramid[i].length; j++) System.out.print(pyramid[i][j] + " "); System.out.print("\n"); } The console output 0 1 2 3 4 5 6 7 8 9 Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 36 Code that uses foreach loops to print a jagged array for (int[] row : pyramid) { for (int col : row) System.out.print(col + " "); System.out.print("\n"); } Murach’s Beg. Java 2, JDK 5, C10 © 2005, Mike Murach & Associates, Inc. Slide 37