Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 61 Arrays Chapter 6. 2 Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define.

Similar presentations


Presentation on theme: "Chapter 61 Arrays Chapter 6. 2 Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define."— Presentation transcript:

1 Chapter 61 Arrays Chapter 6

2 2 Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that return an array learn the proper use of an array as an instance variable learn about multidimensional arrays

3 Chapter 63 Objectives, cont. (optional) learn about text fields and text areas in applets (optional) learn to draw arbitrary polygons and polylines in applets

4 Chapter 64 Outline Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays (optional) Graphics Supplement

5 Chapter 65 Introduction to Arrays An array is an object used to store a (possibly large) collection of data. All the data stored in the array must be of the same type. An array object has a small number of predefined methods.

6 Chapter 66 Introduction to Arrays, cont. Sometimes you want to know several things about a collection of data: –the average –the number of items below the average –the number of items above the average –etc. This requires all the items to be stored as variables of one kind or another.

7 Chapter 67 Introduction to Arrays, cont. Arrays satisfy this need. Even though an array is an object in Java, it can be convenient to think of it as a collection of variables of the same type.

8 Chapter 68 Array Basics: Outline Creating and Accessing Arrays Array Details The length Instance Variable Initializing Arrays

9 Chapter 69 Creating and Accessing Arrays example double[] temperature = new double[7]; is like declaring seven variables of type double, named temperature[0], temperature[1], temperature[2], temperature[3], temperature[4], temperature[5], temperature[6].

10 Chapter 610 Creating and Accessing Arrays, cont. These variables can be used just like any other variables of type double. examples temperature[3] = 32.0; temperature[6] = temperature[3] + 5; System.out.println(temperature[6]); temperature[index] = 66.5; These variables are called indexed variables, elements, or subscripted variables.

11 Chapter 611 Creating and Accessing Arrays, cont. The integer expression within the square brackets is called the index (or subscript).

12 Chapter 612 Creating and Accessing Arrays, cont. class ArrayOfTemperatures

13 Chapter 613 Creating and Accessing Arrays, cont.

14 Chapter 614 Array Details syntax for creating an array Base_Type[] Array_Name = new Base_Type[Length]; example int[] pressure = new int[100]; or int[] pressure; pressure = new int[100];

15 Chapter 615 Array Details, cont. The type of the elements is called the base type. The base type of an array can be any type including a class type. –for example, Species[] entry = new Species[3]; The number of elements is the length or size of the array.

16 Chapter 616 Brackets [] Brackets [] serve three purposes: –creating the type name example: int[] pressure; –creating the new array pressure = new int[100]; –naming an indexed variable of the array pressure[3] = keyboard.nextInt();

17 Chapter 617 Array Terminology

18 Chapter 618 Singular Array Names Whether an array holds singular primitive types or singular class types, singular names make the code more self-documenting. –for example, entry[2] makes more sense than entries[2].

19 Chapter 619 The length Instance Variable An array has only one public instance variable, length. The length variable stores the number of elements the array can hold. Using Array_Name.length typically produces clearer code than using an integer literal.

20 Chapter 620 The length Instance Variable, cont class ArrayOfTemperatures2

21 Chapter 621 Indices and length The indices of an array start with 0 and end with Array_Name.length-1. When a for loop is used to step through an array, the loop control variable should start at 0 and end at length-1. example for (lcv = 0; lcv < temperature.length; lcv++)

22 Chapter 622 Array Index Out of Bounds Every index must evaluate to an integer which is not less than 0 and not greater than Array_Name.length-1. Otherwise, the index is said to be out of bounds or invalid. An out-of-bounds index will produce a run- time error.

23 Chapter 623 Incomplete Array Processing Loops fail to process an entire array correctly when they –begin with an index other than 0 –end with an index other than length-1. Examples for (i = 1; i < oops.length-1; index++) for (i = 1; i <= oops.length; index++) for (i = 0; i <= oops.length; index++) for (i = 0; i < oops.length-1; index++)

24 Chapter 624 Initializing Arrays An array can be initialized at the time it is declared. example double[] reading = {3, 3, 15.8, 9.7}; –The size of the array is determined by the number of values in the initializer list.

25 Chapter 625 Initializing Arrays, cont. Uninitialized array elements are set to the default value of the base type. However, it’s better to use either an initializer list or a for loop. int[] count = new int[100]; for (int i = 0, i < count.length, i++) { count[i] = 0; }

26 Chapter 626 Arrays in Classes and Methods Arrays can be used as instance variables in classes. Both an indexed variable of an array and an entire array can be a argument of a method. Methods can return an indexed variable of an array or an entire array.

27 Chapter 627 Case Study: Using an Array as an Instance Variable Prepare a sales report showing –which sales associate (or associates) has the highest sales –how each associate’s sales compare to the average. needed for each associate –name –sales figures

28 Chapter 628 Case Study: Using an Array as an Instance Variable, cont. tasks –obtain the data ( getFigures ) –update the instance variables ( update ) –display the results (displayResults)

29 Chapter 629 Case Study: Using an Array as an Instance Variable, cont. class SalesAssociate

30 Chapter 630 Case Study: Using an Array as an Instance Variable, cont. The program uses an array to keep track of the data for all sales associates.

31 Chapter 631 Case Study: Using an Array as an Instance Variable, cont. class SalesReporter

32 Chapter 632 Case Study: Using an Array as an Instance Variable, cont. class SalesReporter, contd.

33 Chapter 633 Case Study: Using an Array as an Instance Variable, cont.

34 Chapter 634 Indexed Variables as Method Arguments An indexed variable can be used anywhere that any other variable of the base type of the array can be used. Hence, an indexed variable can be an argument to a method.

35 Chapter 635 Indexed Variables as Method Arguments, cont. class ArgumentDemo

36 Chapter 636 Indexed Variables as Method Arguments, cont. –Note that the results would be the same if the arguments provided to method average were interchanged.

37 Chapter 637 Indexed Variables as Method Arguments, cont.

38 Chapter 638 Array Subtleties If the base type of an array is a primitive type, then a method to which an array element is passed creates a copy of the array element, and cannot change the original array element. If the base type of an array is a class type, then a method to which an array element is passed creates an alias, and the referenced object can be changed.

39 Chapter 639 Entire Arrays as Method Arguments An entire array can be used as a single argument passed to a method. example double[] a = new double[10]; SampleClass.change(a);... public static void change(double[] d) –No brackets accompany the argument. –Method change accepts an array of any size.

40 Chapter 640 Arguments for the Method main Recall the heading for method main : public static void main(String[] args) Method main takes an array of String values as its argument.

41 Chapter 641 Arguments for the Method main, cont. An array of String values can be provided in the command line. example java TestProgram Mary Lou –args[0] is set to “Mary” –args[1] is set to “Lou” System.out.println(“Hello “ + args[0] + “ “ + args[1]); prints Hello Mary Lou.

42 Chapter 642 Use of = and == with Arrays The assignment operator = and the equality operator ==, when used with arrays, behave the same as when used with other objects. –The assignment operator creates an alias, not a copy of the array. –The equality operator determines if two references contain the same memory address, not if two arrays contain the same values.

43 Chapter 643 Making a Copy of an Array example int[] a = new int[50]; int[] b = new int[50];... for (int j = 0; j < a.length; j++) b[j] = a[j];

44 Chapter 644 Determining the “Equality” of Two Arrays To determine if two arrays at different memory locations contain the same elements in the same order, define an equals method which determines if –both arrays have the same number of elements –each element in the first array is the same as the corresponding element in the second array.

45 Chapter 645 Determining the “Equality” of Two Arrays, cont. A while loop can be used. –A boolean variable match is set to true. –Each element in the first array is compared to the corresponding element in the second array. –If two elements are different, match is set to false and the while loop is exited. –Otherwise, the loop terminates with match still set to true.

46 Chapter 646 Determining the “Equality” of Two Arrays, cont. class TestEquals

47 Chapter 647 Determining the “Equality” of Two Arrays, cont.

48 Chapter 648 Methods that Return Arrays A method can return an array. The mechanism is basically the same as for any other returned type. example public static Base_Type[] Method_Name (Parameter_List) Base_Type Array_Name; … return Array_Name; The method need not be public or static.

49 Chapter 649 Methods that Return Arrays, cont. class ReturnArrayDemo

50 Chapter 650 Programming with Arrays and Classes: Outline Programming Example Partially Filled Arrays Searching an Array

51 Chapter 651 Programming Example: A Specialized List Class An array can be an instance variable of a class that is accessible only through the class methods. We will define a class whose objects store lists of items, such as a grocery list or a list of things to do. We’ll name the class OneWayNoRepeatsList.

52 Chapter 652 some features of the class –a method for adding an item to the list unless it is on the list already –an array of strings to hold the items –numbering starting with 1 rather than 0 Programming Example: A Specialized List Class, cont.

53 Chapter 653 Programming Example: A Specialized List Class, cont. –a maximum list size –accessor and mutator methods, but no methods for changing or deleting items –a method to erase the entire list

54 Chapter 654 Using Class OneWayNowRepeatsList Let’s discover how OneWayNoRepeatsList works before considering the definition of the class.

55 Chapter 655 Using Class OneWayNowRepeatsList, cont. class ListDemo

56 Chapter 656 Using Class OneWayNowRepeatsList, cont.

57 Chapter 657 More Features of the Class We need a means of determining that the end of the list has been reached. –Let toDoList.getEntryAt(position) return the value null.

58 Chapter 658 More Features of the Class, cont. class OneWayNoRepeatsList

59 Chapter 659 More Features of the Class, cont. class OneWayNoRepeatsList, contd.

60 Chapter 660 More Features of the Class, cont. three ways to detect the end of a list –when the array is at capacity –when position is at the last entry –when position advances beyond the last entry and null is returned

61 Chapter 661 Partially Filled Arrays Sometimes you need some, but not all of the indexed variables in an array. In such situations, it is important to keep track of how much of the array has been used and/or the index of the last entry so that only meaningful values are accessed.

62 Chapter 662 Partially Filled Arrays, cont.

63 Chapter 663 Searching an Array Method onList in class OneWayNoRepeatsList searches the array entry to see if parameter item is in the array entry. This is an example of a sequential search of an array. –The array elements are examined from first to last to see in an item is in the array already.

64 Chapter 664 Returning an Array Instance Variable If a array reference variable can be copied, the elements of the array can be accessed, perhaps improperly, and changed using the alias, even if the array has a private designation. Even when a copy of the array is provided, if its base type is not a primitive type or type String, its elements can be changed unless they, too, are copied.

65 Chapter 665 Sorting Arrays: Outline Selection Sort Other Sorting Algorithms

66 Chapter 666 Sorting Arrays Sometime we want numbers in an array sorted from smallest to largest, or from largest to smallest. Sometimes we want the strings referenced by an array to be in alphabetical order. Sorting techniques typically are easy to adapt to sort any type that can be ordered.

67 Chapter 667 Selection Sort The selection sort arranges the values in an an array so that a[0] <= a[1] <= a[2] … <= a[a.length-1] The selection sort places the smallest item in a[0], the next smallest item in a[1], and so on for all but the last item. for(i = 0; i <a.length-1; i++) place the i th smallest item in a[i]

68 Chapter 668 Selection Sort, cont. Selection sort begins by finding the smallest item in the array and swapping it with the item in a[0]. Selection sort continues by finding the smallest item in the remainder of the array and swapping it with the next item in array a. Selection sort terminates when only one item remains.

69 Chapter 669 Selection Sort, cont.

70 Chapter 670 Selection Sort, cont. class SelectionSort

71 Chapter 671 Selection Sort, cont. class SelectionSortDemo

72 Chapter 672 Selection Sort, cont.

73 Chapter 673 Swapping Elements To swap two elements a[i] and a[j], one of them must be saved temporarily.

74 Chapter 674 Swapping Elements, cont. class interchange

75 Chapter 675 Other Sorting Algorithms The selection sort is not particularly efficient, but it is easy to code. More efficient algorithms, such as quicksort, are more difficult to code.

76 Chapter 676 Multidimensional Arrays Introduction to Multidimensional Arrays Multidimensional-Array Basics Multidimensional-Array Parameters and Returned Values Implementation of Multidimensional Arrays (optional) Ragged Arrays Programming Example

77 Chapter 677 Introduction to Multidimensional Arrays An array with more than one index sometimes is useful. example: savings account balances at various interest rates for various numbers of years –columns for interest rates –rows for years This two-dimensional table calls for a two- dimensional array.

78 Chapter 678 Introduction to Multidimensional Arrays, cont.

79 Chapter 679 Introduction to Multidimensional Arrays, cont.

80 Chapter 680 Introduction to Multidimensional Arrays, cont. An array with n indices is called an n- dimensional array. The arrays we considered previously, which had one index, were one-dimensional arrays.

81 Chapter 681 Multidimensional-Array Basics example declaration int[][] table = new int [10][6]; or int[][] table; table = new int[10][6]; The number of bracket pairs in the declaration is the same as the number of indices.

82 Chapter 682 Multidimensional-Array Basics, cont. syntax Base_Type[]…[] Array_Name = new Base_Type[Length_1]…[Length_n]; examples char[][] page = new char [100][80]; double[][][] threeDPicture = new double[10][20][30]; SomeClass[][] entry = new SomeClass[100][80];

83 Chapter 683 Multidimensional-Array Basics, cont. Nested for loops can be used to change the values of the elements of the array and to display the values of the elements of the array.

84 Chapter 684 Multidimensional-Array Basics, cont. class InterestTable

85 Chapter 685 Multidimensional-Array Basics, cont.

86 Chapter 686 Multidimensional-Array Parameters Methods may have multidimensional-array parameters.

87 Chapter 687 Multidimensional-Array Parameters, cont. class InterestTable2

88 Chapter 688 Multidimensional-Array Returned Values A method may return a multidimensional array. example public static double[][] corner(double[][] sArray, int i) { double[][] temp = new double[i][i]; … return temp; }

89 Chapter 689 Implementation of Multidimensional Arrays Multidimensional arrays are implemented in Java using one-dimensional arrays. Consider int[][] table = new int[10][6]; –The array table is a one-dimensional array of length 10. –Its base type is int[]. –Therefore, it is an array of arrays.

90 Chapter 690 Implementation of Multidimensional Arrays, cont. This permits us to use the length instance variable, instead of an integer literal, to control a for loop used to initialize or print the values of the elements of an array. example for (r = 0; r < table.length; r++) for (c = 0; c < table[r].length; c++)

91 Chapter 691 Implementation of Multidimensional Arrays, cont. redefined method showTable

92 Chapter 692 Ragged Arrays Since a two-dimensional array in Java is an array of arrays, each row can have a different number of elements (columns). Arrays in which rows have different numbers of elements are called ragged arrays.

93 Chapter 693 Ragged Arrays, cont. Example int[][] b = new int[3][]; b[0] = new int[5]; b[1] = new int[7]; b[2] = new int[4];

94 Chapter 694 Programming Example: Employee Time Records Two-dimensional array hours stores hours worked by each employee for each of the five workdays. –Each row represents a day of the work week, beginning with Monday as day 0. –Each column represents an employee, beginning with employee 1.

95 Chapter 695 Programming Example: Employee Time Records, cont. class TimeBook –includes a stub for method setHours.

96 Chapter 696 Programming Example: Employee Time Records, cont. class TimeBook, contd.

97 Chapter 697 Programming Example: Employee Time Records, cont.

98 Chapter 698 Programming Example: Employee Time Records, cont.

99 Chapter 699 (optional) Graphics Supplement: Outline Part 1: Text Areas and Text Fields Part 2: Drawing Polygons and Polylines

100 Chapter 6100 Text Areas and Text Fields A text area is a window that can be used for text input and text output. –any number of lines –any number of characters per line A text field allows only one line of characters. Text area and text fields provide areas for changeable text in a GUI.

101 Chapter 6101 Programming Example: A Question and Answer Applet The applet accepts a question, requests some advice, and provides an answer. The applet contains some advice for the first user, but then takes the advice provided by one user, and uses it to answer the next user.

102 Chapter 6102 Programming Example:, cont. class Oracle

103 Chapter 6103 Programming Example:, cont.

104 Chapter 6104 JTextArea Objects A text area is an object of the class JTextArea. A JTextArea can be created with private JTextArea theText; … theText = new JTextArea(LINES, CHAR_PER_LINE); Typically, this occurs inside the init method.

105 Chapter 6105 JTextArea Objects, cont. The text in the text area can be read using String question = theText.getText(); The text in the text area can be set using theText.setText(“That’s difficult.\n” + “I need some advice.\n” + “Give me some advice and click.”); –Text can be entered in excess of the specified size, but may not be entirely visible.

106 Chapter 6106 JTextField Objects A text field is an object of the class JTextField. A JTextField can be created with private JTextField theText; … theText = new JTextField(NUMBER_OF_CHARS); Typically, this occurs inside the init method.

107 Chapter 6107 JTextField Objects, cont. The text in the text field can be read using String question = theText.getText(); The text in the text area can be set using theText.setText(“That’s all, folks.”); –Text can be entered in excess of the specified size, but may not be entirely visible.

108 Chapter 6108 Drawing Polygons and Polylines The methods drawPolygon and fillPolygon allow you to draw polygons which are closed figures made of of line segments that meet at vertices but do not cross. A polyline is similar to a polygon, but uses the method drawPolyline and need not be closed.

109 Chapter 6109 Drawing Polygons and Polylines, cont.

110 Chapter 6110 Drawing Polygons and Polylines, cont. class House

111 Chapter 6111 Drawing Polygons and Polylines, cont.

112 Chapter 6112 Method drawPolygon “syntax” canvas.drawPolygon(Array_of_xs, Array_of_ys, Number_of_Points); example private int[] xCoord = {150, 150, 200, 250, 250}; private int[] yCoord = {100, 40, 20, 40, 100}; … canvas.drawPolygon(xCoord, yCoord, xCoord.length);

113 Chapter 6113 Method fillPolygon “syntax” canvas.fillPolygon(Array_of_xs, Array_of_ys, Number_of_Points); example private int[] xCoord = {150, 150, 200, 250, 250}; private int[] yCoord = {100, 40, 20, 40, 100}; … canvas.fillPolygon(xCoord, yCoord, xCoord.length);

114 Chapter 6114 Method drawPolyline “syntax” canvas.drawPolyline(Array_of_xs, Array_of_ys, Number_of_Points); example private int[] xCoord = {150, 150, 200, 250, 250}; private int[] yCoord = {100, 40, 20, 40, 100}; … canvas.drawPolyline(xCoord, yCoord, xCoord.length);

115 Chapter 6115 Method drawPolyline, cont. There is no automatic line segment from the last point to the first point. As a consequence, the figure typically is not closed. A polyline cannot be filled.

116 Chapter 6116 Summary You have learned about arrays and how to use them in Java programs. You have learned how to use array parameters and how to define methods that return an array. You have learned the proper use of an array as an instance variable. You have learned about multidimensional arrays.

117 Chapter 6117 Summary, cont. (optional) You have learned about text fields and text areas in applets. (optional) You have learned to draw arbitrary polygons and polylines in applets.


Download ppt "Chapter 61 Arrays Chapter 6. 2 Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define."

Similar presentations


Ads by Google