Arrays - PowerPoint PPT Presentation

About This Presentation
Title:

Arrays

Description:

An array has only one public instance variable, length. ... Case Study: Using an Array as an Instance Variable, cont. tasks. obtain the data (getFigures) ... – PowerPoint PPT presentation

Number of Views:48
Avg rating:3.0/5.0
Slides: 73
Provided by: rober854
Category:
Tags: arrays | study | time

less

Transcript and Presenter's Notes

Title: Arrays


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 double7
  • is like declaring seven variables of type double,
    named
  • temperature0, temperature1, temperature2,
    temperature3, temperature4, temperature5,
    temperature6.

10
Creating and Accessing Arrays, cont.
  • These variables can be used just like any other
    variables of type double.
  • examples
  • temperature3 32.0
  • temperature6 temperature3 5
  • System.out.println(temperature6)
  • temperatureindex 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_TypeLength
  • example
  • int pressure new int100
  • or
  • int pressure
  • pressure new int100

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 Species3
  • 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 int100
  • naming an indexed variable of the array
  • pressure3 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,
  • entry2
  • makes more sense than
  • entries2.

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.

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 lt temperature.length lcv)

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 lt oops.length-1 index)
  • for (i 1 i lt oops.length index)
  • for (i 0 i lt oops.length index)
  • for (i 0 i lt 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, its better to use either an initializer
    list or a for loop.
  • int count new int100
  • for (int i 0, i lt count.length, i)
  • counti 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 associates 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 double10
  • 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.

41
Arguments for the Method main, cont.
  • An array of String values can be provided in the
    command line.
  • example
  • java TestProgram Mary Lou
  • args0 is set to Mary
  • args1 is set to Lou
  • System.out.println(Hello args0
  • args1)
  • 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 int50
  • int b new int50
  • ...
  • for (int j 0 j lt a.length j)
  • bj aj

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.
  • Well name the class OneWayNoRepeatsList.

52
Programming Example A Specialized List Class,
cont.
  • 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

53
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
Using Class OneWayNowRepeatsList
  • Lets 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.

65
Sorting Arrays Outline
  • Selection Sort
  • Other Sorting Algorithms

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.

67
Selection Sort
  • The selection sort arranges the values in an an
    array so that
  • a0 lt a1 lt a2 lt aa.length-1
  • The selection sort places the smallest item in
    a0, the next smallest item in a1, and so on
    for all but the last item.
  • for(i 0 i lta.length-1 i)
  • place the ith smallest item in ai

68
Selection Sort, cont.
  • Selection sort begins by finding the smallest
    item in the array and swapping it with the item
    in a0.
  • 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
Selection Sort, cont.
70
Selection Sort, cont.
  • class SelectionSort

71
Selection Sort, cont.
class SelectionSortDemo
72
Selection Sort, cont.
73
Swapping Elements
  • To swap two elements ai and aj, one of them
    must be saved temporarily.

74
Swapping Elements, cont.
  • class interchange

75
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
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
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
Introduction to Multidimensional Arrays, cont.
79
Introduction to Multidimensional Arrays, cont.
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.

81
Multidimensional-Array Basics
  • example declaration
  • int table new int 106
  • or
  • int table
  • table new int106
  • The number of bracket pairs in the declaration is
    the same as the number of indices.

82
Multidimensional-Array Basics, cont.
  • syntax
  • Base_Type Array_Name
  • new Base_TypeLength_1Length_n
  • examples
  • char page new char 10080
  • double threeDPicture
  • new double102030
  • SomeClass entry
  • new SomeClass10080

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.

84
Multidimensional-Array Basics, cont.
  • class InterestTable

85
Multidimensional-Array Basics, cont.
86
Multidimensional-Array Parameters
  • Methods may have multidimensional-array
    parameters.

87
Multidimensional-Array Parameters, cont.
  • class InterestTable2

88
Multidimensional-Array Returned Values
  • A method may return a multidimensional array.
  • example
  • public static double corner(double
    sArray, int i)
  • double temp new doubleii
  • return temp

89
Implementation of Multidimensional Arrays
  • Multidimensional arrays are implemented in Java
    using one-dimensional arrays.
  • Consider
  • int table new int106
  • The array table is a one-dimensional array of
    length 10.
  • Its base type is int.
  • Therefore, it is an array of arrays.

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 lt table.length r)
  • for (c 0 c lt tabler.length c)

91
Implementation of Multidimensional Arrays, cont.
  • redefined method showTable

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.

93
Ragged Arrays, cont.
  • Example
  • int b new int3
  • b0 new int5
  • b1 new int7
  • b2 new int4

94
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
Programming Example Employee Time Records, cont.
  • class TimeBook
  • includes a stub for method setHours.

96
Programming Example Employee Time Records, cont.
  • class TimeBook, contd.

97
Programming Example Employee Time Records, cont.
98
Programming Example Employee Time Records, cont.
99
(optional) Graphics Supplement Outline
  • Part 1 Text Areas and Text Fields
  • Part 2 Drawing Polygons and Polylines

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.

101
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
Programming Example, cont.
  • class Oracle

103
Programming Example, cont.
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.

105
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(Thats 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
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
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(Thats all, folks.)
  • Text can be entered in excess of the specified
    size, but may not be entirely visible.

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.

109
Drawing Polygons and Polylines, cont.
110
Drawing Polygons and Polylines, cont.
  • class House

111
Drawing Polygons and Polylines, cont.
112
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
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
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
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
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
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.
Write a Comment
User Comments (0)
About PowerShow.com