"
•
•
#
•
%
&
'
•
"
$
(
)
*
+
* #
$
* ,
-
$
'
•
%
'
(
'
*
'
*
'
.
•
/
' $
•
0
•
%
'
'
(
•
0
0 '
$
•
12
•
(
(
•
3
0
$
( '
•
4
•
&
'
* %
java.util
.
(
import java.util.ArrayList;
/**
* ...
*/
public class Notebook
{
// Storage for an arbitrary number of notes.
private ArrayList notes;
/**
* Perform any initialization required for the
* notebook.
*/
public Notebook()
{
notes = new ArrayList();
}
(
•
$
$
•
.
5
size()
6
•
.
•
7
(
0
* 7
'
8 7
.
0
0
( '
8
public class Notebook
{
private ArrayList notes;
...
public void storeNote(String note)
{
notes.add(note);
}
public int numberOfNotes()
{
return notes.size();
}
...
Adding a new note
Returning the number of notes
(
delegation
).
9
Index validity checks
Retrieve and print the note
public void showNote(int noteNumber)
{
if(noteNumber < 0) {
// This is not a valid note number.
}
else if(noteNumber < numberOfNotes()) {
System.out.println(notes.get(noteNumber));
}
else {
// This is not a valid note number.
}
9 '
' $ ((
'
9
0
•
0
$
'
(
•
$
-•
3
•
ArrayList
( '
java.util
.
9
0
•
'
' $
'
•
1
'
2
•
2
' $
(
'
'
5
(
'
6
•
%
'
ArrayList
'
•
(
0
( '
'
$
'
( '
* 1 4
. : 0
'
$
8
•
"
' '
' .
•
(
'
*
0
(
while(
loop condition
) {
loop body
}
while(
there is at least one more note to be printed
) {
Boolean test
while
keyword
Statements to be repeated
Pseudo-code example to print every note
General form of a while loop
2 '
/**
* List all notes in the notebook.
*/
public void listNotes()
{
int index = 0;
while(index < notes.size()) {
System.out.println(notes.get(index));
index++;
}
}
Increment by one
Iterator it = myCollection.iterator();
while(it.hasNext()) {
call
it.next()
to get the next object
do something with that object
}
java.util.Iterator
Returns an
object
Iterator
public void listNotes()
{
Iterator it = notes.iterator();
while(it.hasNext()) {
%
•
%
(
(
•
%0
(
(
0
)
* %
null
*
(
get
)
9
0
•
#
'
0
. (
'
•
0
0
$
2
•
Iterator
'
($
0
2
- +
•
, '
'
' 2 ' '
+
-
'
•
' '
$ ((
( 2
- +
$
)
•
$
'
- $
•
$
$
2
%
•
(
•
,
0
'
3
.
* "
*
* : 0 '
*
.
(
•
$+
$
$
public class LogAnalyzer
{
private int[] hourCounts;
private LogfileReader reader;
public LogAnalyzer()
{
hourCounts = new int[24];
reader = new LogfileReader();
}
...
}
Array object creation
Array variable declaration
$
•
,&
-
.
$
'
)
hourCounts[...]
•
1 '
.
$
*
(
(
'
)
•
hourCounts[hour] = ...;
*
2
)
•
adjusted = hourCounts[hour] – 3;
•
hourCounts[hour]++;
%
(
•
, '
0
•
(
( 2
'
( '
-for(
initialization
;
condition
;
post-body action
) {
statements to be repeated
}
General form of a for loop
Equivalent in while-loop form
initialization
;
while(
condition
) {
statements to be repeated
post-body action
2 '
for(int hour = 0; hour < hourCounts.length; hour++) {
System.out.println(hour + ": " + hourCounts[hour]);
}
int hour = 0;
while(hour < hourCounts.length) {
System.out.println(hour + ": " + hourCounts[hour]);
hour++;
for loop version
9
0
•
$
0
( 2
-+
&
•
$
$
2
•
((
0
0
'
(
.
0
•
(
$