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
8. Arrays 8.1 Using Arrays 8.2 Reference versus Value Again 8.3 Passing Array Arguments and Returning Arrays 8.4 An Example: Simulating Rolls of the Dice 8.6 Solving Problem with Java: Insertion Sort Objectives • • • • Know how to create and use Java arrays Understand that array variables hold references Copy arrays and pass array arguments Implement insertion sort using an array to hold the data Arrays • Arrays are objects that help us to organize large amount of information • An array is an ordered list of values • The entire array has a single name • Each value has a numeric index • An array of size n is indexed from zero to n-1 • For example, an array of size 10 holds values that are indexed from 0 to 9 Arrays • A particular value in an array is referenced using the array name followed by the index in brackets • For example, the expression score[2] refers to the value 94 (which is the 3rd value in the array) • That expression represents a place to store a single integer, and can be used whenever an integer variable can • For example, it can be assigned a value, printed, or used in a calculation Arrays • An array stores multiple values of the same type • That type can be primitive types or objects • Therefore, we can create an array of integers, or an arrays of characters, or an array of String objects, etc. • In Java, the array itself is an object • Therefore, the name of the array is an object reference variable, and the array itself is instantiated separately score[0] score[1] score[2] 74 38 92 Figure 8.2 The score array if (score1 == 90) System.out.println("It's score1"); else if (score2 == 90) System.out.println("It's score2"); else if (score3 == 90) System.out.println("It's score3"); Figure 8.3 Searching using int variables for if (int i = 0; i < 3; i++) (score[i} == 90) System.out.println("It's at index " + i); Figure 8.4 Searching using an array for (int i = 0; i < score.length; i++) if (score[i} == 90) System.out.println("It's at index " + i); Figure 8.5 Search any size score array Declaring Arrays • The scores array could be declared in one of the following two ways: int[ ] score = new int[10]; int score[ ] = new int[10]; • The first way is preferred • Note that the type of the object does not specify its size, but each object of that type has a specific size • The type of the variable score is int[ ] (an array of integer) Declaring Arrays • Some more examples : double[ ] price = new double[500]; boolean[ ] flag; flag = new boolean[20]; Bound Checking • Each array has a public constant called length that stores the size of the array. It is referenced using the name of the array (just like any other object): score.length • Note that length holds the number of elements, not the largest index Initializer Lists • An initializer list can be used to instantiate and initialize an array in one step • The values are delimited by braces and separated by commas • Examples char[ ] vowel = {'a', 'e', 'i', 'o', 'u'}; String[ ] day = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; Initializer Lists • Note that when an initializer list is used, the new operator is not used • No size value is specified • The size of the array is determined by the number of items in the initializer list • An initializer list can only be used in the declaration of an array Array Examples • • • • • ReverseArray.java ArrayCopy.java LetterCount.java (extra) Calendar.java (extra) Primes.java (extra) {56, 91, 22, 87, 49, 89, 65} L R swap 56 and 65 {65, 91, 22, 87, 49, 89, 56} L R swap 91 and 89 {65, 89, 22, 87, 49, 91, 56} L R swap 22 and 49 {65, 89, 49, 87, 22, 91, 56} L R reverse completed Figure 8.7 Reversing the array of Example 8.1 Initialize the array; Initialize L to the smallest index; Initialize R to the largest index; while (L < R) { Swap the array elements at positions L and R; Increment L; Decrement R; } Output the reversed array; Figure 8.8 Pseudocose to reverse an array score temp int score = 80; 80 ? temp = score; 80 80 Figure 8.9 Primitive types hold values 23 73 score Figure 8.10 Memory usage for score 92 1 2 3 4 5 int[]x={1,2,3,4,5}; x int[]y; y a. Before the assignment x 1 2 3 4 5 y = x y b. After the assignment, y = x Figure 8.11 Memory usage for an array assignment x 1 2 -38 4 5 y Figure 8.12 Memory usage after the assignment y[2] = -38 anArray Figure 8.13 Memory usage for anArray andArray Figure 8.14 memory allocation using the operator new andArray 17 10 Figure 8.15 Figure 8.15 Memory configuration for anArray 22 x 14 72 -8 y 14 72 -8 Figure 8.17 Copying array elements public static void display(int [] anArray) { System.out.print9"{"); for (int I = 0; I < anArray.length; i++) { if (I != 0) System.out.print(anArray[i]); } System.out.println("}"); } Figure 8.18 The display method Arrays as Method Parameters • An entire array can be passed to a method as a parameter • Like any other object, the reference to the array is passed, making the argument and the corresponding parameter aliases of each other • The method accesses the same array as the invoking method • Changing an array element in the method changes the original Arrays as Method Parameters • An array element can be passed to a method as well, and will follow the parameter passing rules of that element's type • DisplayArray.java • RepeatReverse.java • Dice.java score 40 50 60 anArray Figure 8.19 Passing the score reference to the anArray parameter public static int[] readIntArray() { String input = JoptionPane.showInputDialog(“Enter the array size”); int size = Integer.parseInt(input); int [] anArray = new int[size]; for (int i=0; i<size; i++){ input = JOptionPane.showInputDialog(“Enter anArray[“+i+”] ”); anArray[i] = Integer.parseInt(input); } return anArray; } Figure 8.20 The readIntArray method public static void reverse(int[] anArray) { int temp; // used to store a value during a swap int left = 0; // index of the left element to swap int right = anArray.length -1; // index of the right //element to swap while (left < right) { temp = anArray[left]; anArray[left] = anarray[right]; anArray[right] = temp; right--; left++; } } Figure 8.21 The reverse method score 60 50 40 anArray left right Figure 8.22 Reversing the score array 27 x 27 someNumber Figure 8.23 Memory configuration after passing x to assign4 27 x 4 someNumber Figure 8.24 Effect of the assign4 method 1 2 3 4 5 6 1 2 3 4 5 6 7 2 3 4 5 6 7 8 3 4 5 6 7 8 9 4 5 6 7 8 9 10 5 6 7 8 9 10 11 6 7 8 9 10 11 12 Figure 8.25 Outcomes when tossing two dice Command-Line Arguments • The signature of the main method indicates that it takes an array of String objects as a parameter public static void main(String[ ] args) • These values come from command-line arguments that are provided when the interpreter is invoked • For example, the following invocation of the interpreter passes an array of three String objects into main: java DoIt illinois texas california Command-Line Arguments • These strings are stored at indexes 0-2 of the parameter • NameTag.java (extra) student Student[2] 52 98 43 76 65 87 93 77 62 Student[3] 72 73 74 Student[0] Student[1] Figure 8.26 The student array Insertion Sort • The approach: – pick any item and insert it into its proper place in a sorted sublist – repeat until all items have been inserted • In more detail: – consider the first item to be a sorted sublist (of one item) – insert the second item into the sorted sublist, shifting items as necessary to make room to insert the new addition – insert the third item into the sorted sublist (of two items), shifting as necessary – repeat until all values are inserted into their proper position Insertion Sort • An example: – – – – – original: insert 9: insert 6: insert 1: insert 2: 3 3 3 1 1 9 9 6 3 2 6 6 9 6 3 1 1 1 9 6 2 2 2 2 9 23 42 54 78 26 12 41 64 Figure 8.27 Partially sorted array Get the data to sort; Display the data to sort; Insert each item in the correct position in its predecessors; Display the sorted data; Figure 8.28 Insertion Sort: Top-level pseudocode Ask if the user wants to enter data; if (yes) Get data from the user; else Generate random data; Figure 8.29 Refinement: Get the data to sort Input the size of the data; loop Get the next item; Figure 8.30 Refinement: Get data from the user Input the size of the data; Ask if the user wants to enter the data; if (yes) loop Get the next item; else loop Generate the next random item; Figure 8.31 Revised refinement: Get the data to sort loop, from second item to last Insert item i in the correct position in its predecessors; Figure 8.32 Refinement: Insert items Find the correct position, say j, for item i; Move elements at j to i-1 one position to the right; Insert item i at position j. 8.33 Refinement: Insert item i j = 0; while (item i > item j) j++; Figure 8.34 Refinement: Finding the correct position for item i Save item i; for (int k = i; k > j; k--) item[k] = item[k - 1]; Figure 8.35 Refinement: Move elements j to i-l to the right Input the size of the data; Ask if the user wants to enter the data; if (yes) loop Get the next item; else loop Generate the next random item; Figure 8.36 Pseudocode for insertion sort Display the data to sort; loop, from second item to last { j = 0; while (item i > item j) j++; Save item i; for (int k = i; k > j; k--) item[k] = item[k - l]; item[j] = item[i]; } Display the sorted data; Figure 8.36 Pseudocode for insertion sort (continued) Insertion Sorting public static void insertionSort (int[ ] number) { for (int i = 1; i < number.length; i++) { int key = number[i]; // shift larger values to the right for (int j = i - 1; j >= 0 && number[j] > key; j--) number[j + 1] = number[j]; number[j+1] = key; } } Time (milliseconds) 20,000 15,000 10,000 5,000 1,000 5,000 10,000 15,000 20,000 Data size Figure 8.37 Rate of growth of insertion sort (0,0) 100-item[2] (0,100) 2*width Figure 8.38 Part of a bar chart Interfaces • A Java interface is a collection of abstract methods and constants • An abstract method is a method header without a method body • An abstract method can be declared using the modifier abstract, but because all methods in an interface are abstract, it is usually left off • An interface is used to formally define a set of methods that a class will implement Interfaces public interface Doable { public void doThis(); public int doThat(); public void doThis2(double value); public boolean doTheOther(int num); } Interfaces • An interface cannot be instantiated • Methods in an interface have public visibility by default • A class formally implements an interface by stating so in the class header, and providing implementations for all abstract methods in the interface Interfaces public class canDo implements Doable { public void doThis() { // whatever } public void doThat() { // whatever } // etc. } Interfaces • A class that implements an interface can implement other methods as well Speaker.java (extra) Philosopher.java (extra) Dog.java (extra) Talking.java (extra) • A class can implement multiple interfaces • The interfaces are listed in the implements clause, separated by commas • The class must implement all methods in all interfaces listed in the header Generic Sorting • Integers have an inherent order • An order must be defined in a set of objects for them to be sorted • The Comparable interface contains only the compareTo abstract method which is used to compare two objects • We can use the Comparable interface to develop a generic sort for a set of objects • The String class implements Comparable which gives us the ability to put strings in alphabetical order Generic Insertion Sorting public static void insertionSort (Comparable[ ] object) { for (int i = 1; i < object.length; i++) { Comparable key = object[i]; // shift larger values to the right for (int j = i - 1; j >= 0 && object[j].compareTo(key) > 0; j--) object [j + 1] = object[j]; object[j+1] = key; } }