Presentation is loading. Please wait.

Presentation is loading. Please wait.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Arrays.

Similar presentations


Presentation on theme: "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Arrays."— Presentation transcript:

1 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Arrays

2 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Objectives After you have read and studied this chapter, you should be able to Manipulate a collection of data values, using an array. Declare and use an array of primitive data types in writing a program. Declare and use an array of objects in writing a program.

3 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Objectives, cont. After you have read and studied this chapter, you should be able to Define a method that accepts an array as its parameter and a method that returns an array. Describe how a two-dimensional array is implemented as an array of arrays. Manipulate a collection of objects, using lists and maps.

4 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics In Java, an array is an indexed collection of data values of the same type. Arrays are useful for sorting and manipulating a collection of values.

5 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.1 Sample array: Monthly rainfall averages and their variation from the annual average.

6 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics Square brackets [] are used to declare an array. To declare an array, we may attach the brackets to either the data type or the variable name. An array named rainfall of type double, may be stated either as double [] rainfall; or double rainfall [];

7 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics In Java, an array is a reference data type. We use the new operator to allocate the memory to store the values in an array. rainfall = new double [12]; //creates an array of size 12.

8 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.2 An array of 12 double values.

9 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics We use a single identifier to refer to the whole collection in the array. We use an indexed expression to refer to the individual values of the collection. Arrays use zero-based indexing. An individual value in an array is called an array element.

10 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.3 An array of 12 double values after all 12 are assigned values.

11 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics An array has a public constant length for the size of an array. for (i=0; i<rainfall.length; i++) {... } This approach is particularly useful when the size of an array may change, or is not known in advance.

12 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics Do not confuse the length value of an array and the length method of a String object. The length is a method for a String object, so we use the syntax for calling a method. String str = “This is a string”; int size = str.length();

13 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics An array, on the other hand, is a reference data type, not an object. Therefore, we do not use a method call. int size = rainfall.length;

14 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics We can initialize the array at the time it is declared: String[] monthName = { “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December” }; Because the array is initialized here, it is unnecessary to state the size of the array. The size is determined by the number of values in the list.

15 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics Using constants to declare the array sizes does not always lead to efficient use of space. Declaration of arrays with constants is called fixed- size array declaration. Fixed-size array declaration may pose two problems: Not enough capacity for the task at hand. Wasted space.

16 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics In Java, we are not limited to fixed-size array declaration. The following code prompts the user for the size of an array and declares an array of designated size: int size; int[] number; size= Integer.parseInt( JOptionPane.showInputDialog(null, “Size of an array:”)); number = new int[size];

17 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.1 Array Basics Any valid integer arithmetic expression is allowed for specifying the size of an array: size = Integer.parseInt( JOptionPane.showInputDialog(null,””)); number = new int[size*size + 2*size + 5];

18 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects Arrays are not limited to primitive data types. We will use the Person class to illustrate this concept. An array of objects is declared and created just as an array of primitive data types is. Person[] person; person = new Person[20];

19 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.4 An array of Person objects after the array is created.

20 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects Array elements are initially null. Since each array element is an object, each must also be created. person[0] = new Person( );

21 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects class Person { private String name; private int age; private char gender; public Person() { this("Not Given", 0, 'U'); } public Person(String name, int age, char gender) { this.age = age; this.name = name; this.gender = gender; } // see the lecture code for more behavior // setXXX, getXXX, etc. }

22 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.5 The person array with one Person object added to it.

23 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects To assign data values to this object, we can execute person[0].setName (“Ms. Latte”); person[0].setAge (20); person[0].setGender (‘F’); The syntax here is the one used to call an object’s method; we are using an indexed expression to refer to the object instead of a simple variable.

24 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects The following program illustrates various aspects of array processing: Creating a new person array. Creating a new Person object and assigning values to it. Finding the average age of the persons in the array. Finding the youngest and oldest persons in the array. Finding a particular person in the array.

25 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects /* Chapter 10 Sample Program: Illustrate the processing of an array of Person objects File: Ch10ProcessPersonArray.java */ import javax.swing.*; class Ch10ProcessPersonArray { public static void main (String[] args) { Person[] person; //declare the person array person = new Person[5]; //and then create it

26 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects //----------- Create person Array ------------// String name, inpStr; int age; char gender; for (int i = 0; i < person.length; i++) { //read in data values name = JOptionPane.showInputDialog(null, "Enter name:"); age = Integer.parseInt( JOptionPane.showInputDialog(null, "Enter age:")); inpStr =JOptionPane.showInputDialog(null, "Enter gender:"); gender = inpStr.charAt(0);

27 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects //create a new Person and assign values person[i] = new Person( ); person[i].setName ( name ); person[i].setAge ( age ); person[i].setGender( gender ); } //------ Compute Average Age --------------// float sum = 0, averageAge; for (int i = 0; i < person.length; i++) { sum += person[i].getAge(); } averageAge = sum / (float) person.length; System.out.println("Average age: " + averageAge); System.out.println("\n");

28 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects //-- Find the youngest and oldest person ------// //-- Approach No. 3: Using person reference ---// Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { //found a younger person youngest = person[i]; } else if (person[i].getAge() > oldest.getAge() ) { //found an older person oldest = person[i]; } System.out.println("Oldest : " + oldest.getName() + " is " + oldest.getAge() + " years old.");

29 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects System.out.println("Youngest: " + youngest.getName() + " is " + youngest.getAge() + " years old."); //----- Search for a particular person ------// String searchName = JOptionPane.showInputDialog(null, "Name to search:"); int i = 0; while (i<person.length && !person[i].getName().equals(searchName)) { //still more persons to search i++; }

30 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects if (i == person.length) { //not found - unsuccessful search System.out.println( searchName + " was not in the array" ); } else { //found - successful search System.out.println("Found " + searchName + " at position " + i); }

31 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.6 An array of Person objects with two Person variables.

32 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects Deleting objects from an array requires us to search for the Person object to be removed. When the object is located, there are two ways to delete the object.

33 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects The first approach is to set the array element to null. Because each array element is a reference to an object, setting the element to null accomplishes this task easily.

34 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.7 Approach 1 deletion: Setting a reference to null. The array length is 4.

35 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects Any index position may be set to null, but this approach creates “holes” in the array. The second approach to deleting an object will order the elements so the real references occur at the beginning and the null references at the end.

36 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects Packing the elements so the real references occur at the beginning and the null references occur at the end.

37 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects We must fill the holes. There are two possible approaches: If an object at position J is removed (i.e., set to null), then elements from position J+1 up to the last non-null reference are shifted one position lower. Finally, the last non-null reference is set to null. Replace the removed element by the last element in the array.

38 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.8 Approach 2 deletion: Replace the removed element with the last element in the array. The array length is 4.

39 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects Note that assigning null to an array element will not erase the object. This operation does initiate a chain reaction that will eventually erase the object from memory.

40 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects A single object may have multiple references pointing to it: Person p1, p2; p1 = new Person( ); p2 = p1;

41 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.2 Arrays of Objects When an object has no references pointing to it, the system will erase the object and make the memory space available again. Erasing an object is called deallocation of memory. The process of deallocating memory is called garbage collection. Garbage collection is automatically performed in Java.

42 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.3 Passing Arrays to Methods Arrays and objects are reference data types, so the rules for passing an object to a method and returning an object from a method apply to arrays. Consider an example method that returns the index of the smallest element in an array of real numbers:

43 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.3 Passing Arrays to Methods public int searchMinimum(double[] number) { int indexOfMinimum = 0; for (int i = 1; i < number.length; i++){ if (number[i] < number[indexOfMinimum]) { //found a smaller element indexOfMinimum = i; } return indexOfMinimum; } To call this method (from a method of the same class), we write

44 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.3 Passing Arrays to Methods double[] arrayOne; //create and assign values to arrayOne... //get the index of the smallest element of arrayOne int minOne = searchMinimum(arrayOne); //output the result System.out.print(“Minimum value in Array One is ”); System.out.print(arrayOne[minOne] + “at position ” + minOne);...

45 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.3 Passing Arrays to Methods Remember that when an array is passed to a method, only its reference is passed. A copy of the array is not created in the method.

46 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.9A Passing an array to a method means we are passing a reference to an array.

47 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.9B Passing an array to a method means we are passing a reference to an array.

48 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.10A Passing an array to a method means we are passing a reference to an array.

49 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.10B Passing an array to a method means we are passing a reference to an array.

50 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.3 Passing Arrays to Methods Next we will consider an example in which we return an array from a method. This method inputs double values and returns the values as an array of double.

51 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.3 Passing Arrays to Methods public double[] readDoubles() { double[] number; int N = Integer.ParseInt( JOptionPane.showInputDialog(null, “How many input values?”)); number = new double[N]; for (int i = 0; i<N; i++){ number[i] = Double.parseDouble( JOptionPane.showInputDialog(null, “Number ” + i)); } return number; }

52 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.3 Passing Arrays to Methods The readDoubles method is called: double[] arrayOne; //assign values to arrayOne arrayOne = readDoubles(); Because a new array is created by the method, we do not have to create an array from the calling side. Doing so will not cause an error, but it is a wasteful operation.

53 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.3 Passing Arrays to Methods Figures 10.11 and 10.12 examine the effects of creating a local array and not returning it.

54 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.11A The effect of creating a local array and not returning it.

55 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.11B The effect of creating a local array and not returning it.

56 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.12A The effect of creating a local array and not returning it.

57 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.12B The effect of creating a local array and not returning it.

58 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.5 Two-Dimensional Arrays In Java, data may be organized in a two- dimensional array. A table is an example of a two-dimensional array. In a two-dimensional array, two indices (in a table, one for the row and one for the column) are used to refer to the array element.

59 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.5 Two-Dimensional Arrays To declare our example array, we state: double[][] payScaleTable; or double payScaleTable[][]; and create the array as payScaleTable = new double[4][5];

60 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.15 Examples of information represented as tables.

61 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.5 Two-Dimensional Arrays To refer to an element at the second column (column 1) of the third row (row 2), we say payScaleTable[2][1] Nested-for loops are useful for manipulating two- dimensional arrays.

62 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.16 Accessing an element of a two-dimensional array.

63 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.5 Two-Dimensional Arrays The concept of the two-dimensional array in Java is just that: a concept. There is no explicit structure called the “two-dimensional array” in Java. The two-dimensional array concept is implemented by using an array of arrays.

64 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.5 Two-Dimensional Arrays The sample array creation payScaleTable = new double[4][5]; is a shorthand for payScaleTable = new double [4][ ]; payScaleTable[0] = new double [5]; payScaleTable[1] = new double [5]; payScaleTable[2] = new double [5]; and so on.

65 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.17A Executing the statements on the left in sequence will create the array of arrays shown on the right.

66 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 10.17B

67 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.5 Two-Dimensional Arrays The expression payScaleTable.length refers to the length of the payScaleTable array itself.

68 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.5 Two-Dimensional Arrays The expression payScaleTable[1].length refers to the length of the array stored at row 1 of payScaleTable.

69 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.5 Two-Dimensional Arrays An array that is part of another array is called a subarray. An array of arrays may be initialized when it is created. int i[][]={{1,2,3},{5,6,7},{0,9,8,7}};

70 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.5 Two-Dimensional Arrays Subarrays may be different lengths. Executing triangularArray = new double[4][ ]; for (int i = 0; i < 4; i++) triangularArray[i] = new double [i + 1]; results in an array that looks like:

71 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps The java.util library contains high-power classes for maintaining a collection of objects. These classes are collectively referred to as the Java Collection Framework (JCF).

72 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps The List interface is one useful feature that can help us manage large numbers of objects. An interface defines the behavior of a class; a list of public methods without method bodies. We cannot create an instance of an interface.

73 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps Two classes in the JCF implement the List interface: ArrayList LinkedList The ArrayList class uses an array to manage data. The LinkedList class uses a technique called linked-node representation.

74 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps To use the List interface, we declare the variable as List and assign an instance of the class that implements the List interface to it: List myList;... myList = new ArrayList( ); This approach permits a quick change of the implementation class if necessary.

75 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps The default constructor will create an empty list with an initial capacity of 10. It is possible to increase the capacity of a list. However, it is better to create a list with the actual capacity we need, if we know in advance what that capacity is.

76 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps The add method allows us to add objects to the list. Person person = new Person(); friends.add(person); The capacity method gives us the current capacity of a list. int capacity = friends.capacity(); To find out the number of objects contained in a list, we use its size method. int size = friends.size();

77 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps The remove method takes an element’s index as its parameter and allows us to remove an element from a list. friends.remove(4); The get method allows us to access objects stored in a list by giving their index position in the list. Person person = (Person) friends.get(3); The iterator method also allows us to scan the elements inside a list or other JCF collection classes.

78 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps When we call a list’s iterator method, an Iterator object (an instance of a class that implements the Iterator interface) that supports two methods, hasNext and next, is returned. hasNext returns true if the iterator has more elements to access. Calling next if there are no more elements to access will result in an error. Person person; Iterator iterator = friends.iterator( ); while ( iterator.hasNext( ) ) { person = (Person) iterator.next( ); System.out.println( person.getName( ) ); }

79 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps The iterator method is supported by many other java.util classes. A list cannot include primitive data values as its elements, but wrapper classes can adapt the values to acceptable list objects.

80 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps Two classes implement the Map interface: HashMap TreeMap TreeMap implements a subinterface of Map called SortedMap, where the entries in the map are sorted.

81 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps A map consists of entries. Each entry is divided into two parts: key value Duplicate keys are not allowed in the map. Both the key and the value may be instances of any class.

82 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps A map may be characterized as an expandable array with instances of any class as its indices. The main advantage of a map is its performance in locating an entry, given the key.

83 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps We create an instance of a map: Map table;... table = new TreeMap(); We add the key-value pairs to the map: table.put(“COMP150”, “Great course. Take it.”); The first argument is the key. The second argument is the value.

84 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps To remove an entry from a map, we use its remove method and pass the key as the argument. To retrieve all entries in the map, we use the entrySet method. To access all entries in a map, we use the entrySet method to obtain a set of entries, then use the iterator method as in the ArrayList example.

85 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps The getKey and getValue methods are two particularly useful methods in the interface. These method retrieve the map entry’s key and value, respectively.

86 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 10.6 Lists and Maps SortedMap table = new TreeMap(); //... Map.Entry entry; Iterator itr = table.entrySet().iterator(); while (itr.hasNext()) { entry = (Map.Entry) itr.next(); line = entry.getValue().toString() + "\t" + entry.getKey() + “\n”; strBuf.append(line); }


Download ppt "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Arrays."

Similar presentations


Ads by Google