Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 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 methods that return an array learn the proper use of an array as an instance variable learn about multidimensional arrays

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

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

5 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 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 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 Array Basics: Outline Creating and Accessing Arrays Array Details The length Instance Variable Initializing Arrays

9 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 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+1] = 66.5; These variables are called indexed variables, elements, or subscripted variables.

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

12 Creating and Accessing Arrays, cont. class ArrayOfTemperatures

13 Creating and Accessing Arrays, cont.

14 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 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 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 Array Terminology

18 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 The length Instance Variable An array has only one public instance variable, namely 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 The length Instance Variable, cont class ArrayOfTemperatures2

21 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; index++)

22 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 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 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 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++) a[i] = 0;

26 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 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 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 Case Study: Using an Array as an Instance Variable, cont. class SalesAssociate

30 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 Case Study: Using an Array as an Instance Variable, cont. class SalesReporter

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

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

34 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 Indexed Variables as Method Arguments, cont. class ArgumentDemo

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

37 Indexed Variables as Method Arguments, cont.

38 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 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 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. A default array of String values is when you run a program.

41 Arguments for the Method main, cont. Alternatively, 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 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 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 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 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 Determining the “Equality” of Two Arrays, cont. class TestEquals

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

48 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 Methods that Return Arrays, cont. class ReturnArrayDemo

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

51 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 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 –a maximum list size –accessor and mutator methods, but no methods for changing or deleting items –a method to erase the entire list

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

55 Using Class OneWayNowRepeatsList, cont. class ListDemo

56 Using Class OneWayNowRepeatsList, cont.

57 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 More Features of the Class, cont. class OneWayNoRepeatsList

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

60 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 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 Partially Filled Arrays, cont.

63 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 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.


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

Similar presentations


Ads by Google