Outline
7.1
7.2
7.3
7.4
7.5
7.6
7.7
7.8
7.9
7.10
Introduction
Arrays
Declaring and Creating Arrays
Examples Using Arrays
References and Reference Parameters
Passing Arrays to Methods
Sorting Arrays
Searching Arrays: Linear Search and Binary Search
Multidimensional Arrays
(Optional Case Study) Thinking About Objects:
Collaboration Among Objects
7.1
Introduction
Arrays
Data structures
Related data items of same type
Remain same size once created
Fixed-length entries
7.2
Array
Group of variables
Have same type
Reference type
Arrays
Name of array
(note that all
elements of this
array have the
same name, c)
Fig. 7.1
2003 Prentice Hall, Inc. All rights reserved.
c[ 0 ]
-45
c[ 1 ]
c[ 2 ]
c[ 3 ]
72
c[ 4 ]
1543
c[ 5 ]
-89
c[ 6 ]
c[ 7 ]
62
c[ 8 ]
-3
c[ 9 ]
c[ 10 ]
6453
c[ 11 ]
78
A 12-element array.
7.2
Arrays (cont.)
Index
Also called subscript
Position number in square brackets
Must be positive integer or integer expression
a = 5;
b = 6;
c[ a + b ] += 2;
Adds 2 to c[ 11 ]
7.2
Arrays (cont.)
Examine array c
c is the array name
c.length accesses array cs length
c has 12 elements ( c[0], c[1], c[11] )
The value of c[0] is 45
7.3
7.4
Declaring arrays
Creating arrays
Initializing arrays
Manipulating array elements
7.4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
InitArray.java
Create 10 ints for array; each
Declare array
asinitialized
an
int is
to 0 by defaultLine 9
public static void main( String args[]
) of ints
array
Declare array as an
{
int array[];
// declare reference to an array
array of ints
array.length returns
array = new int[ 10 ]; // create array
length of array
Line 11
System.exit( 0 );
} // end main
Outline
InitArray.java
Each int is initialized Each int is
to 0 by default
initialized to 0 by
default
7.4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
Declare array as an
array of ints
InitArray.java
Line 11
public static void main( String args[] )
Compiler uses initializerDeclare
list
{
// array initializer specifies number of elements and to allocate array array of
// value for each element
int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
String output = "Index\tValue\n";
// append each array element's value to String output
for ( int counter = 0; counter < array.length; counter++ )
output += counter + "\t" + array[ counter ] + "\n";
array as an
ints
Line 11
Compiler uses
initializer list to
allocate array
System.exit( 0 );
} // end main
} // end class InitArray
Outline
InitArray.java
Each array element
corresponds to element
in initializer list
7.4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
as an
array of ints
Outline
InitArray.java
Line 10
Create 10 ints for array
Declare array as an
array of ints
// create array
Line 12
Create 10 ints for
array
Line 16
Use array index to
assign array value
26
27
28
29
30
31
32
33
34
Outline
InitArray.java
System.exit( 0 );
} // end main
} // end class InitArray
7.4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Outline
array with
initializer list
SumArray.java
Line 9
Declare array with
initializer list
Lines 13-14
Sum all array values
JOptionPane.showMessageDialog( null,
"Total of array elements: " + total,
"Sum the Elements of an Array",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end main
} // end class SumArray
7.4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Outline
Declare array with
initializer list
Histogram.java
Line 9
Declare array with
initializer list
Line 19
For each array
element, print
associated number of
asterisks
26
27
28
29
30
31
32
33
Outline
Histogram.java
} // end main
} // end class Histogram
7.4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Outline
RollDie.java
Declare frequency
as
array of 7 ints
Line 9
Generate 6000 random
Declare frequency
integers in range 1-6
as array of 7 ints
frequency values at
index associated with random number
String output
// append frequencies to
for ( int face = 1; face < frequency.length; face++ )
output += "\n" + face + "\t" + frequency[ face ];
JTextArea outputArea = new JTextArea();
outputArea.setText( output );
Lines 12-13
Generate 6000
random integers in
range 1-6
Line 13
Increment
frequency values at
index associated with
random number
7.4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Outline
Declare responses as
Declare
frequency as array of 11
array to store
40 responses
StudentPoll.jav
int and ignore the first
element
a
Lines 9-11
Declare responses
as array to store 40
responses
Line 12
Declare frequency
as array of 11 int
For each response, increment
and ignore the first
frequency values at index
element
String output = "Rating\tFrequency\n";
associated with that response
// append frequencies to String output
Lines 16-17
for ( int rating = 1; rating < frequency.length; rating++ )
For each response,
output += rating + "\t" + frequency[ rating ] + "\n";
increment
frequency values at
JTextArea outputArea = new JTextArea();
outputArea.setText( output );
index associated with
that response
// for each answer, select responses element and use that value
// as frequency index to determine element to increment
for ( int answer = 0; answer < responses.length; answer++ )
++frequency[ responses[ answer ] ];
28
29
30
31
32
33
34
35
Outline
StudentPoll.jav
a
7.4
7.5
Pass-by-reference
7.6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Outline
PassArray.java
Line 15
Declare 5-int
array with initializer
list
Line 24
Pass array by
Pass array by reference
to
reference
to method
method modifyArray
modifyArray
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Method modifyArray
manipulates the array directly
Outline
PassArray.java
Line 35
Pass array[3] by
value to method
modifyElement
Lines 43-47
Method
modifyArray
manipulates the array
directly
Lines 50-53
Method
modifyElement
manipulates a
primitives copy
Lines 52
The original primitive
is left unmodified
2003 Prentice Hall, Inc.
All rights reserved.
Outline
PassArray.java
7.7
Sorting Arrays
Sorting data
Attracted intense research in computer-science field
Bubble sort
Smaller values bubble their way to top of array
Larger values sink to bottom of array
Use nested loops to make several passes through array
Each pass compares successive pairs of elements
Pairs are left along if increasing order (or equal)
Pairs are swapped if decreasing order
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Outline
BubbleSort.java
Line 15
Declare 10-int
array with initializer
list
Line 23
Pass array by
reference to method
45, 37 };
bubbleSort
to sort
Pass array by reference to
method
array
bubbleSort to sort array
// sort array
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Outline
BubbleSort.java
outputArea.setText( output );
Line 36
Method
bubbleSort
Method bubbleSort receives
receives array
array reference as parameter
reference as parameter
Lines 39-53
Use loop and nested
Use loop and nested loop to make
loop to make passes
passes through array through array
Lines 48-49
If pairs are in
decreasing order,
invoke method swap
to swap pairs
56
57
58
59
60
61
62
63
64
65
66
67
Outline
// swap two elements of an array
public void swap( int array3[], int first, int second )
{
int hold; // temporary holding area for swap
hold = array3[ first ];
array3[ first ] = array3[ second ];
array3[ second ] = hold;
}
BubbleSort.java
Lines 58-65
Method swap swaps
two values in array
reference
7.8
Searching
Finding elements in large amounts of data
Determine whether array contains value matching key value
Linear searching
Binary searching
7.8
Linear search
Compare each array element with search key
If search key found, return element index
If search key not found, return 1 (invalid index)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Outline
LinearSearch.ja
va
Line 11
Declare array of
ints
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
Outline
LinearSearch.ja
va
Lines 39-42
Allocate 100 ints
// create array and populate with even Create
integers
0 to
198 for array and for array and
100
ints
array = new int[ 100 ];
populate array with even ints populate array with
even ints
for ( int counter = 0; counter < array.length; counter++ )
resultField = new JTextField( 20 );
resultField.setEditable( false );
container.add( resultField );
Line 50
Loop through array
Lines 53-54
If array element at
index matches search
key, return index
at index matches
search key, return index
return -1;
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
Outline
LinearSearch.ja
va
Line 61
Invoked when user
presses Enter
Invoke method linearSearch, using
Line 68
array and search key as arguments
value in element " + element );
Invoke method
linearSearch,
not found" );
using array and
search key as
arguments
7.8
Binary search
Efficient for large, sorted arrays
Eliminates half of the elements in search through each pass
Compare middle array element to search key
If element equals key
Return array index
If element is less than key
Repeat search on first half of array
If element is greater then key
Repeat search on second half of array
Continue search until
element equals search key (success)
Search contains one element not equal to key (failure)
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
BinarySearch.ja
va
import javax.swing.*;
public class BinarySearch extends JApplet implements ActionListener {
JLabel enterLabel, resultLabel;
JTextField enterField, resultField;
JTextArea output;
Declare array of ints
Line 14
Declare array of
ints
int array[];
String display = "";
// set up applet's GUI
public void init()
{
// get content pane and set its layout to FlowLayout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JLabel and JTextField for user input
enterLabel = new JLabel( "Enter integer search key" );
container.add( enterLabel );
enterField = new JTextField( 10 );
container.add( enterField );
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Outline
BinarySearch.ja
va
Lines 48-51
Allocate 15 ints for
array and populate
array with even
// set up JTextArea for displaying comparison data
ints
output = new JTextArea( 6, 60 );
output.setFont( new Font( "Monospaced", Font.PLAIN,
) );for array and
Allocate 1512
ints
container.add( output );
populate array with even intsLine 56
Invoked when user
// create array and fill with even integers 0 to 28
presses Enter
array = new int[ 15 ];
resultField = new JTextField( 20 );
resultField.setEditable( false );
container.add( resultField );
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
Outline
BinarySearch.ja
va
Invoke method binarySearch,
using
Line
65
array and search key as arguments
Invoke method
binarySearch,
using array and
value in element " + element );
search key as
arguments
not found" );
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
Outline
va
Lines 93-94
If search key matches
middle array
middle
element,
on second
half array
If searchrepeat
key issearch
less than
middlearray
array
// key greater than middle element, set new low element
element, return
element, repeat search on first array half
else
element index
low = middle + 1;
Lines 97-98
If search key is less
} // end while
than middle array
return -1;
// key not found
element, repeat search
on first array half
Method buildOutput displays
} // end method binarySearch
Lines 101-102
array contents being searched
// build row of output showing subset of array elements
If search key is greater
// currently being processed
than middle array
void buildOutput( int array3[], int low, int middle, int high )
element, repeat search
{
on second array half
// create 2-digit integer number format
Lines 112-137
DecimalFormat twoDigits = new DecimalFormat( "00" );
Method buildOutput displays
array contents being
searched
// if key less than middle element, set new high element
else if ( key < array[ middle ] )
high = middle - 1;
If search key is greater than
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
Outline
BinarySearch.ja
va
Line 128
Display an asterisk
next to middle
element
";
} // end for
display += "\n";
Outline
BinarySearch.ja
va
7.9
Multidimensional Arrays
Multidimensional arrays
Tables with rows and columns
Two-dimensional array
Declaring two-dimensional array b[2][2]
int b[][] = { { 1, 2 }, { 3, 4 } };
1 and 2 initialize b[0][0] and b[0][1]
3 and 4 initialize b[1][0] and b[1][1]
int b[][] = { { 1, 2 }, { 3, 4, 5 } };
row 0 contains elements 1 and 2
row 1 contains elements 3, 4 and 5
7.9
Row 0
Row 1
Row 2
Column 0
Column 1
Column 2
Column 3
a[ 0 ][ 0 ]
a[ 0 ][ 1 ]
a[ 0 ][ 2 ]
a[ 0 ][ 3 ]
a[ 1 ][ 0 ]
a[ 1 ][ 1 ]
a[ 1 ][ 2 ]
a[ 1 ][ 3 ]
a[ 2 ][ 0 ]
a[ 2 ][ 1 ]
a[ 2 ][ 2 ]
a[ 2 ][ 3 ]
Column index
Row index
Array name
Fig. 7.13 Two-dimensional array with three rows and four columns.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Outline
InitArray.java
Declare array1 with six Line 16
initializers in two sublists Declare array1 with
six initializers in two
sublists
Declare array2 with six
initializers in three sublists
Line 17
Declare array2 with
six initializers in three
sublists
int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } };
outputArea.setText( "Values in array1 by row are\n" );
buildOutput( array1 );
outputArea.append( "\nValues in array2 by row are\n" );
buildOutput( array2 );
} // end method init
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Outline
Line 34
array[row].leng
th returns number of
columns associated
with row subscript
Line 35
Use double-bracket
notation to access twodimensional array
values
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Outline
Lines 7-9
Declare grades as 3by-4 array
Lines 7-9
Each row represents a
student; each column
represents an exam
grade
// number of students
// number of exams
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Outline
DoubleArray.jav
Determine
a minimum and
maximum for all student
Lines 31-32
Determine minimum
and maximum for all
student
grades
Lines 35-37
Determine average for
each student
Determine average
for each student
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
Outline
return lowGrade;
Lines 54-61
Use a nested loop to
search for lowest
grade in series
Lines 74-81
Use a nested loop to
search for highest
grade in series
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
return highGrade;
Outline
DoubleArray.jav
Method average takes
array of
a
student
test results as parameter
set
of grades)
Line 88
Method average
sum of array elements
takes array of student
test results as
count++ )
parameter
Divide by number of
elements to get average
Lines 93-94
Calculate sum of array
elements
Line 97
Divide by number of
elements to get
average
109
110
111
112
113
114
115
116
117
118
119
120
Outline
DoubleArray.jav
a
}
} // end method buildString
} // end class DoubleArray
Class
Elevator
Verb phrases
resets elevator button, rings elevator bell, signals its
arrival, signals its departure, opens its door, closes its door
ElevatorShaft
turns off light, turns on light, resets floor button
Person
presses floor button, presses elevator button, rides
elevator, enters elevator, exits elevator
FloorButton
summons (requests) elevator
ElevatorButton signals elevator to move to opposite floor
FloorDoor
signals person to enter elevator (by opening)
ElevatorDoor
signals person to exit elevator (by opening), opens floor
door, closes floor door
Fig. 7.16
Verb phrases for each class exhibiting behaviors in
simulation.
An object of class...
Elevator
pressButton( )
: Person
: FloorButton
3.1 : openDoor( )
3.1.1 doorOpened( )
: FloorDoor
4.1 : resetButton( )
: FloorButton
4.2 : turnOnLight( )
: ElevatorShaft
: Light
4 : elevatorArrived( )
: Person
passenger : Person
: Elevator
3.2.1 : exitElevator( )
3.1.1.1 : enterElevator( )
3.2 : doorOpened( )
1: resetButton( )
: ElevatorButton
2: ringBell( )
3: openDoor( )
: Bell
: ElevatorDoor
Fig. 7.19 Collaboration diagram for passengers exiting and entering the elevator.
2003 Prentice Hall, Inc. All rights reserved.
Message 2
Elevator sends ringBell to Bell
Message 3
Elevator sends openDoor to ElevatorDoor
Message 3.1
ElevatorDoor sends openDoor to FloorDoor
Message 3.1.1
FloorDoor sends doorOpened to waitingPassenger
Message 3.1.1.1
waitingPassenger sends enterElevator to
Elevator
2003 Prentice Hall, Inc. All rights reserved.
Message 3.2.1
Person sends exitElevator to Elevator
Message 4
Elevator sends elevatorArrived to ElevatorShaft
Message 4.1
ElevatorShaft sends resetButton to FloorButton
Message 4.2
ElevatorShaft sends turnOnLight to Light