72
Chapter 6 1 Arrays Chapter 6

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

Embed Size (px)

Citation preview

Page 1: 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

Chapter 6 1

Arrays

Chapter 6

Page 2: 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

Chapter 6 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.

Page 3: 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

Chapter 6 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.

Page 4: 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

Chapter 6 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.

Page 5: 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

Chapter 6 9

Creating and Accessing Arrays

• exampledouble[] temperature = new double[7];

is like declaring seven variables of type double, namedtemperature[0], temperature[1], temperature[2], temperature[3], temperature[4], temperature[5], temperature[6].

Page 6: 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

Chapter 6 10

Creating and Accessing Arrays, cont.

• These variables can be used just like any other variables of type double.

• examplestemperature[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.

Page 7: 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

Chapter 6 11

Creating and Accessing Arrays, cont.

• The integer expression within the square brackets is called the index (or subscript).

Page 8: 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

Chapter 6 12

Creating and Accessing Arrays, cont.

• class ArrayOfTemperatures

Page 9: 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

Chapter 6 13

Creating and Accessing Arrays, cont.

Page 10: 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

Chapter 6 14

Array Details

• syntax for creating an arrayBase_Type[] Array_Name =

new Base_Type[Length];

• exampleint[] pressure = new int[100];

orint[] pressure;

pressure = new int[100];

Page 11: 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

Chapter 6 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.

Page 12: 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

Chapter 6 16

Brackets[]

• Brackets [] serve three purposes:– creating the type name

example: int[] pressure;– creating the new arraypressure = new int[100];

– naming an indexed variable of the arraypressure[3] = keyboard.nextInt();

Page 13: 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

Chapter 6 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].

Page 14: 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

Chapter 6 19

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.

Page 15: 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

Chapter 6 20

The length Instance Variable, cont

• class ArrayOfTemperatures2

Page 16: 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

Chapter 6 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.

• examplefor (lcv = 0; lcv < temperature.length; lcv+

+)

Page 17: 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

Chapter 6 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.

Page 18: 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

Chapter 6 24

Initializing Arrays

• An array can be initialized at the time it is declared.

• exampledouble[] reading = {3, 3, 15.8, 9.7};

– The size of the array is determined by the number of values in the initializer list.

Page 19: 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

Chapter 6 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++)

{

count[i] = 0;

}

Page 20: 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

Chapter 6 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.

Page 21: 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

Chapter 6 29

Case Study: Using an Array as an Instance Variable, cont.• class SalesAssociate

Page 22: 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

Chapter 6 31

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

Page 23: 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

Chapter 6 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.

Page 24: 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

Chapter 6 35

Indexed Variables as Method Arguments, cont.

• class ArgumentDemo

Page 25: 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

Chapter 6 39

Entire Arrays as Method Arguments

• An entire array can be used as a single argument passed to a method.

• exampledouble[] 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.

Page 26: 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

Chapter 6 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.

Page 27: 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

Chapter 6 41

Arguments for the Method main, cont.

• An array of String values can be provided in the command line.

• examplejava 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.

Page 28: 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

Chapter 6 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.

Page 29: 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

Chapter 6 43

Making a Copy of an Array

• exampleint[] a = new int[50];

int[] b = new int[50];

...

for (int j = 0; j < a.length; j++)

b[j] = a[j];

Page 30: 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

Chapter 6 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.

Page 31: 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

Chapter 6 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.

Page 32: 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

Chapter 6 46

Determining the “Equality” of Two Arrays, cont.

• class TestEquals

Page 33: 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

Chapter 6 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.

Page 34: 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

Chapter 6 49

Methods that Return Arrays, cont.

• class ReturnArrayDemo

Page 35: 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

Chapter 6 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.

Page 36: 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

Chapter 6 62

Partially Filled Arrays, cont.

Page 37: 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

Chapter 6 66

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.

Page 38: 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

Chapter 6 67

Selection Sort

• The selection sort arranges the values in an an array so thata[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 ith smallest item in a[i]

Page 39: 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

Chapter 6 68

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.

Page 40: 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

Chapter 6 69

Selection Sort, cont.

Page 41: 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

Chapter 6 70

Selection Sort, cont.

• class SelectionSort

Page 42: 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

Chapter 6 73

Swapping Elements

• To swap two elements a[i] and a[j], one of them must be saved temporarily.

Page 43: 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

Chapter 6 74

Swapping Elements, cont.

• class interchange

Page 44: 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

Chapter 6 77

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.

Page 45: 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

Chapter 6 78

Introduction to Multidimensional Arrays, cont.

Page 46: 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

Chapter 6 79

Introduction to Multidimensional Arrays, cont.

Page 47: 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

Chapter 6 80

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.

Page 48: 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

Chapter 6 81

Multidimensional-Array Basics

• example declarationint[][] table = new int [10][6];

orint[][] table;

table = new int[10][6];

• The number of bracket pairs in the declaration is the same as the number of indices.

Page 49: 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

Chapter 6 82

Multidimensional-Array Basics, cont.

• syntaxBase_Type[]…[] Array_Name =

new Base_Type[Length_1]…[Length_n];

• exampleschar[][] page = new char [100][80];

double[][][] threeDPicture =

new double[10][20][30];

SomeClass[][] entry =

new SomeClass[100][80];

Page 50: 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

Chapter 6 83

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.

Page 51: 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

Chapter 6 84

Multidimensional-Array Basics, cont.

• class InterestTable

Page 52: 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

Chapter 6 86

Multidimensional-Array Parameters

• Methods may have multidimensional-array parameters.

Page 53: 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

Chapter 6 87

Multidimensional-Array Parameters, cont.

• class InterestTable2

Page 54: 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

Chapter 6 88

Multidimensional-Array Returned Values

• A method may return a multidimensional array.

• examplepublic static double[][] corner(double[][]

sArray, int i)

{

double[][] temp = new double[i][i];

return temp;

}

Page 55: 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

Chapter 6 89

Implementation of Multidimensional Arrays

• Multidimensional arrays are implemented in Java using one-dimensional arrays.

• Considerint[][] 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.

Page 56: 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

Chapter 6 90

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

Page 57: 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

Chapter 6 91

Implementation of Multidimensional Arrays, cont.• redefined method showTable

Page 58: 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

Chapter 6 92

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.

Page 59: 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

Chapter 6 93

Ragged Arrays, cont.

• Exampleint[][] b = new int[3][];

b[0] = new int[5];

b[1] = new int[7];

b[2] = new int[4];

Page 60: 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

Chapter 6 100

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.

Page 61: 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

Chapter 6 104

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.

Page 62: 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

Chapter 6 105

JTextArea Objects, cont.

• The text in the text area can be read usingString question = theText.getText();

• The text in the text area can be set usingtheText.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.

Page 63: 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

Chapter 6 106

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.

Page 64: 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

Chapter 6 107

JTextField Objects, cont.

• The text in the text field can be read usingString question = theText.getText();

• The text in the text area can be set usingtheText.setText(“That’s all, folks.”);

– Text can be entered in excess of the specified size, but may not be entirely visible.

Page 65: 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

Chapter 6 108

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.

Page 66: 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

Chapter 6 109

Drawing Polygons and Polylines, cont.

Page 67: 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

Chapter 6 110

Drawing Polygons and Polylines, cont.

• class House

Page 68: 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

Chapter 6 111

Drawing Polygons and Polylines, cont.

Page 69: 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

Chapter 6 112

Method drawPolygon

• “syntax”canvas.drawPolygon(Array_of_xs, Array_of_ys, Number_of_Points);

• exampleprivate int[] xCoord = {150, 150, 200, 250, 250};

private int[] yCoord = {100, 40, 20, 40, 100};

canvas.drawPolygon(xCoord, yCoord, xCoord.length);

Page 70: 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

Chapter 6 113

Method fillPolygon

• “syntax”canvas.fillPolygon(Array_of_xs, Array_of_ys, Number_of_Points);

• exampleprivate int[] xCoord = {150, 150, 200, 250, 250};

private int[] yCoord = {100, 40, 20, 40, 100};

canvas.fillPolygon(xCoord, yCoord, xCoord.length);

Page 71: 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

Chapter 6 114

Method drawPolyline

• “syntax”canvas.drawPolyline(Array_of_xs, Array_of_ys, Number_of_Points);

• exampleprivate int[] xCoord = {150, 150, 200, 250, 250};

private int[] yCoord = {100, 40, 20, 40, 100};

canvas.drawPolyline(xCoord, yCoord, xCoord.length);

Page 72: 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

Chapter 6 115

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.