Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 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

3 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

4 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

5 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

6 Figure 8.2 The score array 74 38 92 score[0] score[1] score[2]

7 Figure 8.3 Searching using int variables 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");

8 Figure 8.4 Searching using an array for (int i = 0; i < 3; i++) if (score[i} == 90) System.out.println("It's at index " + i);

9 Figure 8.5 Search any size score array for (int i = 0; i < score.length; i++) if (score[i} == 90) System.out.println("It's at index " + i);

10 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)

11 Declaring Arrays Some more examples : double[ ] price = new double[500]; boolean[ ] flag; flag = new boolean[20];

12 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

13 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"};

14 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

15 Array Examples ReverseArray.java ArrayCopy.java LetterCount.java (extra) Calendar.java (extra) Primes.java (extra)

16 Figure 8.7 Reversing the array of Example 8.1 {56, 91, 22, 87, 49, 89, 65} swap 56 and 65 L R {65, 91, 22, 87, 49, 89, 56} swap 91 and 89 L R {65, 89, 22, 87, 49, 91, 56} swap 22 and 49 L R {65, 89, 49, 87, 22, 91, 56} reverse completed L R

17 Figure 8.8 Pseudocose to reverse an array 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;

18 Figure 8.9 Primitive types hold values 80 ? scoretemp int score = 80; temp = score;

19 Figure 8.10 Memory usage for score 237392 score

20 Figure 8.11 Memory usage for an array assignment a. Before the assignment b. After the assignment, y = x 12345 54321 x y x y int[]x={1,2,3,4,5}; int[]y; y = x

21 Figure 8.12 Memory usage after the assignment y[2] = -38 1 2 4-38 5 x y

22 Figure 8.13 Memory usage for anArray anArray

23 Figure 8.14 memory allocation using the operator new andArray

24 Figure 8.15 Figure 8.15 Memory configuration for anArray andArray 171022

25 x y 14 72 -8 Figure 8.17 Copying array elements

26 Figure 8.18 The display method 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("}"); }

27 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

28 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

29 405060 score anArray Figure 8.19 Passing the score reference to the anArray parameter

30 Figure 8.20 The readIntArray method 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; }

31 Figure 8.21 The reverse 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++; }

32 score anArray 605040 left right Figure 8.22 Reversing the score array

33 Figure 8.23 Memory configuration after passing x to assign4 27 xsomeNumber

34 274 xsomeNumber Figure 8.24 Effect of the assign4 method

35 123456 1234567 2345678 3456789 45678910 56789 11 6789101112 Figure 8.25 Outcomes when tossing two dice

36 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

37 Command-Line Arguments These strings are stored at indexes 0-2 of the parameter NameTag.java (extra)

38 Figure 8.26 The student array student 527665 988793 437762 727374 Student[0] Student[1] Student[2] Student[3]

39 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

40 Insertion Sort An example: –original: 3 9 6 1 2 –insert 9: 3 9 6 1 2 –insert 6: 3 6 9 1 2 –insert 1: 1 3 6 9 2 –insert 2: 1 2 3 6 9

41 2342547826124164 Figure 8.27 Partially sorted array

42 Figure 8.28 Insertion Sort: Top-level pseudocode Get the data to sort; Display the data to sort; Insert each item in the correct position in its predecessors; Display the sorted data;

43 Figure 8.29 Refinement: Get the data to sort Ask if the user wants to enter data; if (yes) Get data from the user; else Generate random data;

44 Figure 8.30 Refinement: Get data from the user Input the size of the data; loop Get the next item;

45 Figure 8.31 Revised refinement: Get the data to sort 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;

46 Figure 8.32 Refinement: Insert items loop, from second item to last Insert item i in the correct position in its predecessors;

47 8.33 Refinement: Insert item i 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.

48 Figure 8.34 Refinement: Finding the correct position for item i j = 0; while (item i > item j) j++;

49 Figure 8.35 Refinement: Move elements j to i-l to the right Save item i; for (int k = i; k > j; k--) item[k] = item[k - 1];

50 Figure 8.36 Pseudocode for insertion sort 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;

51 Figure 8.36 Pseudocode for insertion sort (continued) 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;

52 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; }

53 Figure 8.37 Rate of growth of insertion sort 1,0005,00010,00015,00020,000 15,000 10,000 5,000 Data size Time (milliseconds)

54 100-item[2] (0,100) (0,0) 2*width Figure 8.38 Part of a bar chart

55 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

56 Interfaces public interface Doable { public void doThis(); public int doThat(); public void doThis2(double value); public boolean doTheOther(int num); }

57 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

58 Interfaces public class canDo implements Doable { public void doThis() { // whatever } public void doThat() { // whatever } // etc. }

59 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

60 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

61 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; }


Download ppt "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."

Similar presentations


Ads by Google