Chapter 4
|
Modified: |
Chapter 3 examined fundamental problem solving approaches of modularization and abstraction. Here we will examine some of the ways objects may be grouped together into collections.
Many objects in life come in groups:
- drawer of socks
- list of people to invite to a wedding
- days in a month
- dozen eggs
Some groups are fixed in size while others are flexible size. We need programming features for modeling both cases.
Exercise 1 - NoteBook class In BlueJ
- Open project chapter04\notebook1.
- Click View | Show Terminal
- In Terminal window click Options | Record method calls
- Create a NoteBook object.
- Store two notes:
- "Buy bread"
- "Sell car"
- Check the number of notes stored.
- Show each note. The first note is numbered 0, the second 1, etc.
| Collections - An object that can store a arbitrary number of other objects. |
Examples:
- drawer object can hold arbitrary number of other objects: socks, rocks, spoons, forks, photographs.
- note book object can hold arbitrary number of other objects: shopping list, reminders, class notes, etc. Important that each page is arranged in numerical order, page 0, page 1, ...
- ArrayList object can hold arbitrary number of other objects: Strings, ClockDisplay, etc.
| Class libraries - A class that is already defined and can be used in your program. Similar classes are normally grouped together as a library. |
| Package - What Java calls a library of classes. |
Example packages:
- java.util - Utility classes.
- java.net - Networking classes.
- java.Math - Math classes.
import java.util.ArrayList;
public class Notebook
{
private ArrayList<String> notes;
public NoteBook()
{
notes = new ArrayList<String>();
}
public void storeNote(String note)
{
notes.add( note );
}
public int numberOfNotes()
{
return notes.size();
}
public void showNote(int noteNumber)
{
if(noteNumber < 0) { // Not valid note number, so do nothing.
}
else if( noteNumber < numberOfNotes()) { // Valid note number, so print it.
System.out.println( notes.get( noteNumber ));
}
else { // Not valid note number, so do nothing.
}
}
Using the ArrayList class:
- import java.util.ArrayList; - Gain access to the library.
- private ArrayList<String> notes; - Define field notes as type ArrayList class.
- notes = new ArrayList<String>() - Create an instance of ArrayList.
ArrayList methods:
The ArrayList class supplies many useful methods, we will use four for now:
- add - adds an object to the ArrayList. Example:
- notes.add("Take vacation");
- size - returns the number of objects in the ArrayList. Example (assuming 3 objects):
- notes.size(); returns 3.
- get - returns the ith object in ArrayList. Example:
- notes.get( 2 ); returns the 2nd object from ArrayList notes.
- remove - removes the ith object in the ArrayList. Example (assuming 3 objects):
- notes.remove(1);
ArrayList object notes after the following statements are executed:
- private ArrayList<String> notes;
- notes = new ArrayList();
- notes.add("Buy bread");
- notes.add("Sell car");
Exercise 2 - NoteBook methods In BlueJ
- Inspect the NoteBook object.
- Click on the notes field and Inspect button.
- What is the value of field size?
- What do you think is the value of accessor: notes.size()
- Click on elementData and Inspect button.
- What is the number of:
- "Sell car"
- "Buy bread"
- Call method:
- showNote to show note number 1.
- numberOfNotes.
- Store another note "11:30 mtg"
- What do think is the number of this note?
- What do you think is the value of: notes.size()?
- In what order does ArrayList objects store objects as added?
- Update the object diagram above by hand to include "11:30 mtg" note.

An ArrayList can have elements of any type of object. To define that the notes field must be <String> objects only.
ArrayList<String> notes;
To define a group of TicketMachines:
ArrayList<TicketMachine> tms;
Exercise 2.5 In your head
- Declare a field named library of type ArrayList having elements of type Book.

| index - Position of an object in a collection. |
Examples:
- Index 0 of notes ArrayList object is "Buy bread".
- Index 1 of notes ArrayList object is "Sell car".
Exercise 3 - Indexes For the object diagram:
- What would be the index of the next note added?
- What is:
- notes.size();
- notes.get(1);
- notes.get(0);
- notes.get(5);
- System.out.println( notes.get( 1 ) );
Exercise 4 - remove In your head
- Using the object diagram, what is the index of "11:30 mtg" after:
- notes.remove(1);
- What is the value now of:
- notes.size()
In BlueJ
- Add the mutator method deleteNote that removes the ith index note from the notebook. Assume the ith note exists.
- What is the method signature?
- Does it need an information parameter?
- Does it return anything?
- Which of the signatures is most appropriate?
- int deleteNote()
- void deleteNote()
- void deleteNote(int ith)
- int deleteNote(int ith)
- Create a NoteBook object with 3 notes.
- Inspect the object.
- Inspect notes.
- Inspect elementData.
- Use deleteNote to remove note at index 1.
- Use deleteNote to remove note at index 4.
Exercise 5 - listAllNotes
- Which of the signatures would be most appropriate for a method to print all notes:
- public ArrayList<String> listAllNotes()
- public void listAllNotes(int index)
- public int listAllNotes()
- public void listAllNotes()
In BlueJ
- Add the listAllNotes method using the appropriate signature and the following as the method body. Index 0 holds the first note, index 1 the second, etc.
System.out.println( notes.get(0) );
System.out.println( notes.get(1) );
System.out.println( notes.get(2) );
:- Test the listAllNotes method.
- What is wrong with the above as the body for listAllNotes method?
| for-each loop - Executes a block of statements repeatedly instead of programmer writing repeatedly. Loops scale very well. |

Examples that produce the same result on each row:
Write repeatedly Execute repeatedly int i = 0;
System.out.println( notes.get( i ) );
i = i + 1;
System.out.println( notes.get( i ) );
i = i + 1;
System.out.println( notes.get( i ) );for ( String note : notes )
System.out.println( note );
Exercise 5.5 In your head
- What is the result of the above for the object at right?
In BlueJ
- Change listAllNotes to use a for-each loop.
| while loop - Executes a block of statements repeatedly instead of programmer writing repeatedly. Loops scale very well. |
Examples that produce the same result on each row:
Write repeatedly Execute repeatedly int i = 0; // Add 1 to i 4 times
i = i + 1;
i = i + 1;
i = i + 1;
i = i + 1;int i = 0; // Add 1 to i 4 times
while ( i < 4 ) {
i = i + 1;
}int i = 4; // Subtract 1 from i 4 times
i = i - 1;
i = i - 1;
i = i - 1;
i = i - 1;int i = 4; // Subtract 1 from i 4 times
while ( i >= 1 ) {
i = i - 1;
}int i = 0;
i = i + 1;
System.out.println( i );
i = i + 1;
System.out.println( i );
i = i + 1;
System.out.println( i );
i = i + 1;
System.out.println( i );int i = 0;
while ( i < 4 ) {
i = i + 1;
System.out.println( i );
}int i = 0;
System.out.println( i );
i = i + 1;
System.out.println( i );
i = i + 1;
System.out.println( i );
i = i + 1;
System.out.println( i );
i = i + 1;int i = 0;
while ( i < 4 ) {
System.out.println( i );
i = i + 1;
}System.out.println( notes.get(0) );
System.out.println( notes.get(1) );
System.out.println( notes.get(2) );
System.out.println( notes.get(3) );
int i = 0;
while ( i < 4 ) {
System.out.println( notes.get( i ) );
i = i + 1;
}if (notes.size() >= 0)
System.out.println( 0 + ":" + notes.get(0) );
if (notes.size() >= 1)
System.out.println( 1 + ":" + notes.get(1) );
if (notes.size() >= 2)
System.out.println( 2 + ":" + notes.get(2) );
if (notes.size() >= 3)
System.out.println( 3 + ":" + notes.get(3) );int i = 0;
while ( i < notes.size() ) {
System.out.println( i + ":" + notes.get( i ) );
i = i + 1;
}
Exercise 6 - listAllNotes
- Which of the above would be most appropriate for the body of your listAllNotes method?
In BlueJ
- Copy and paste the appropriate body for listAllNotes method into NoteBook class.
- Create an instance with 2 notes and call the listAllNotes method.
- Modify listAllNotes method to print the notes in reverse order.
- Create an instance with 2 notes and call the listAllNotes method.
- Modify deleteNote to print out an error message if the note number parameter is not valid.
Infinite loopsLooping is a powerful tool but has the danger of looping infinitely (i.e. the loop never stops). A simple example of an infinite loop that prints "Forever..." forever till stopped externally is:
while( true )
System.out.println( "Forever...");
Exercise 6.1 - Infinite loops In BlueJ
- Copy and paste the following method into the NoteBook class.
public void infinite()
{
int i=0;
while( true ) {
System.out.println( i + " Forever...");
i=i+1;
}
}
- Test by creating a NoteBook object and calling the method.
- Stop by:
- Pressing Ctrl-Shift-R keys simultaneously.
- or
- Right click
. It may take a little time to respond.
- Click Reset Virtual Machine.
- or
- Ctrl-Shift-Delete keys simultaneously and use the Task Manager.
- End the java.exe process.
- BlueJ can become unstable when reset. Suggest closing and restarting BlueJ.
| iterator - An object that provides the ability to iterate over every element in a collection. |
Examples that all produce the same results (assuming notes.size() == 3):
System.out.println( notes.get(0) );
System.out.println( notes.get(1) );
System.out.println( notes.get(2) );Iterator<String> i = notes.iterator();
System.out.println( i.next( ) );
System.out.println( i.next( ) );
System.out.println( i.next( ) );int i = 0;
while ( i < notes.size() ) {
System.out.println( notes.get( i ) );
i = i + 1;
}Iterator<String> i = notes.iterator();
while ( i.hasNext() ) {
System.out.println( i.next() );
}

Exercise 7 - Iterators
- From the diagram at right, what is printed by:
Iterator<String> theIter = notes.iterator();
System.out.println( theIter.next( ) );
- From the diagram at right, what is printed by:
Iterator<String> it = notes.iterator();
System.out.println( it.hasNext( ) );
- What is printed by:
Iterator<String> it = notes.iterator();
System.out.println( it.next( ) );
System.out.println( it.next( ) );
System.out.println( it.next( ) );System.out.println( it.hasNext( ) );
- index - notes.get( 3 ); The index allows any object in the collection to be accessed in any order.
- iterator - notes.next( ); The iterator access is strictly sequential order.
The following classes define a Person with an age and name, and a Party class that groups Person objects. The class definitions follow:
public class Person
{
private int age;
private String name;
public Person(int age, String newName) {
this.age=age;
name=newName;
}
public int getAge() {
return age;
}
public void printPerson() {
System.out.print("Name: " + name);
Systen.out.println(" Age: " + age );
}
}import java.util.ArrayList;
import java.util.Iterator;
public class Party
{
private ArrayList <Person> guests;
public Party() {
guests = new ArrayList <Person> ();
}
public void arrive( Person partier ) {
guests.add( partier );
}
public void indexPrintParty() {
int i = 0;
while (i < guests.size())
{
guests.get(i).printPerson();
i = i + 1;
}
}
public void iteratorPrintParty() {
Iterator <Person> git = guests.iterator();
while ( git.hasNext() )
git.next().printPerson();
}
}
Exercise 7.1 - Example In your head
Give the object diagram for the following:
Person p0 = new Person(23, "George");
Person p1 = new Person(29, "Sally");ArrayList <Person> guests = new ArrayList <Person> ();
guests.add( p0 );
guests.add( p1 );In BlueJ
- Create a new project named Exercise 7.1
- Create a new class named Person
Copy and paste the Person class above.
- Create a new class named Party
Copy and paste the Party class above.
- Duplicate in BlueJ the results of the following:
Person p0 = new Person(23, "George");
Person p1 = new Person(29, "Sally");Party wedding = new Party();
wedding.arrive( p0 );
wedding.arrive( p1 );
- Give the object diagram for Question 4.
The following two examples produce identical results:
Person p0 = new Person(23, "George");
Person p1 = new Person(29, "Sally");guests = new ArrayList <Person> ();
guests.add( p0 );
guests.add( p1 );guests = new ArrayList <Person> ();
guests.add( new Person(23, "George") );
guests.add( new Person(29, "Sally") );On the right, anonymous objects are created eliminating the need to define variables p0 and p1.
| array - A collection that can store a fixed number of elements (objects or primitive-type). Uses a special syntax to access elements in the collection. |
- Assignment - x[ index ] = y;
- Copy - y = x[ index ];
int x0;![]() int x1; int x2; x0 = -3; |
int [ ] x = new int [ 3 ];![]() x[ 0 ] = -3;
|
![]() String notes0 ; |
![]() String notes[ ] = new String[3]; notes[ 0 ] = "Buy bread"; |
![]() ArrayList notes = new ArrayList( ); notes.add( "Buy bread" ); |
![]() String notes[ ] = new String[3]; notes[ 0 ] = "Buy bread"; |
| System.out.println( notes.get(0) ); System.out.println( notes.get(1) ); System.out.println( notes.get(2) ); |
System.out.println( notes[ 0 ] ); System.out.println( notes[ 1 ] ); System.out.println( notes[ 2 ] ); |
| int i = 0; while ( i < notes.size() ) { System.out.println( notes.get( i ) ); i = i + 1; } |
int i = 0; while ( i < notes.length ) { System.out.println( notes[ i ] ); i = i + 1; } |
Exercise 8 - Fixed size collections String notes[ ] = new String[3];
notes[ 0 ] = "Buy bread";
notes[ 1 ] = "Sell car";
notes[ 2 ] = "11:30 mtg";
- From the diagram at right, what is the result:
- String s = notes[ 2 ];
- notes[ 1 ] = notes[ 0 ];
- notes[ 2 ] = "Take a break";
- notes[ 3 ] = "Broke";
- notes[ -1 ] = "Broke";
- From the diagram at right, what is printed by:
int i = 2;
while ( i >= 0 ) {
System.out.println( i + notes[ i ] );
i = i - 1;
}
- Define the object pages, an array 4 ints, see the figure at right.
- Initialize index 2 of pages to 15.
- Give the statements to print the figure at right.
Examples:
- Declare an array variable hours that can refer to an array of ints:
- int[ ] hours;
- Declare an array variable months that can refer to an array of Strings:
- String[ ] months;
Examples:
- Create an array of 24 ints and assign to hours:
hours = new int[24];

- Create an array of 12 Strings and assign to months:
months = new String[12];
Exercise 9 - Arrays
- Write a declaration for an array variable people that can refer to an array of Person objects.
- Assign variable people an array of 30 Person objects.
- Write a declaration for an array variable vacant that can refer to an array of booleans.
- Assign variable vacant an array of 13 booleans.
- Write a declaration for an array variable dim that can refer to an array of ints.
- Assign dim an array of 12 ints.
| Indexing - Accessing individual variables of an array using the [ ]. |
Examples:
- Assign hours index 20 value 54:
hours[20] = 54;

- Assign months index 2 value "March":
months[2] = "March";
- Add hours index 23 value to variable count:
count = count + hours[23];
- Print months index 2 value:
System.out.println(months[2]);
Exercise 10 - Using Arrays
- Initialize each variable (i.e. index) of dim with the number of days in January, February, etc. for this year.
- Sum index 5, 6 and 7 of dim to variable summer.
- Print index 5, 6 and 7 of dim.
| for-loop - Iterates from a starting value to an ending value in designated steps. |
Examples that produce the same result:
ArrayList <String> notes = new ArrayList <String> (); notes.add( "Buy bread" ); |
![]() String notes[ ] = new String[3]; notes[ 0 ] = "Buy bread"; |
| int i = 0; while ( i < notes.size() ) { System.out.println( notes.get( i ) ); i = i + 1; } |
int i = 0; while ( i < notes.length ) { System.out.println( notes[ i ] ); i = i + 1; } |
| int i; for ( i=0; i < 3 ; i++) { System.out.println( notes.get( i ) ); } |
int i; for ( i=0; i < 3; i++ ) { System.out.println( notes[ i ] ); } |
| int i; for ( i=0; i < notes.size() ; i++) { System.out.println( notes.get( i ) ); } |
int i; for ( i=0; i < notes.length; i++ ) { System.out.println( notes[ i ] ); } |
Examples:
- Print all the integers from 3 to 12
int i;
for ( i = 3; i <=12; i++)
System.out.println( i );
- Total all the hourCounts variables to sumHours:
int sumHours = 0;
for ( int i = 0; i < 24; i++)
sumHours = sumHours + hourCounts[ i ];
- Print all variables in array hourCounts:
for ( int i = 0; i < 24; i++)
System.out.println( hourCounts[ i ]);
- Find largest value in array dim:
int largest = dim[0];
for ( int i = 0; i < 12; i++)
if ( dim[ i ] > largest )
largest = dim[ i ];
- Find smallest value in array dim:
int smallest = dim[0];
for ( int i = 0; i < 12; i++)
if ( dim[ i ] < smallest )
smallest = dim[ i ];
Exercise 11 - for loop with Arrays
- Print all the integers from 12 to 3.
- Print all variables in array hourCounts in reverse order.
- Print all the variables in array dim.
- Print all the variables in array dim in reverse order.
- Total all the variables in array dim.
- Find smallest value in array hourcounts.
Web-servers log client visits to web pages.
Analyzing the log file can determine:
- popular pages
- broken links (missing pages)
- server usage
- busy periods
We have a web log file in the format of:
year month day hour minute
2009 5 01 00 19
2009 5 01 01 27
2009 5 01 02 17
public class LogAnalyzer
{
private int[ ] hourCounts;
private LogfileReader reader;
public LogAnalyzer()
{
hourCounts = new int[24];
reader = new LogfileReader();
}
public void analyzeHourlyData()
{
while(reader.hasMoreEntries() ) {
LogEntry entry = reader.nextEntry();
int hour = entry.getHour();
hourCounts[hour]= hourCounts[hour] + 1;
}
}
public void printHourlyCounts()
{
System.out.println("Hr: Count");
for(int hour = 0; hour < hourCounts.length; hour=hour+1)
{
System.out.println(hour + ": " + hourCounts[hour]);
}
}
public void printData()
{
reader.printData();
}
} Web log file format: year month day hour minute
2009 3 01 00 19
2009 3 01 01 17
2009 3 01 01 22
2009 3 01 01 25
2009 3 01 01 42
2009 3 01 01 57
2009 3 01 02 17LogAnalyzer - Constructor
hourCounts - Assigned object of fixed array of 24 ints.
reader - Assigned LogfileReader object.
analyzeHourlyData - Fills hoursCount array with total of the number of visits
within an hour period.
For example, adds 1 to array index 5 of hourCounts for a log entry
at 5 o'clock. Consider when hour = 5:
int hour = entry.getHour();
hourCounts[hour]=hourCounts[hour]+1;printHourlyCounts - Prints each of the 24 variables in the hourCounts array.
The hoursCount array prints as:0:0
1:5
2:0
3:0
4:2
:
:

The following creates the array at right:
private int[ ] hourCounts;
public LogAnalyzer()
{
hourCounts = new int[24];
}
printHourlyCounts - Prints each of the 24 variables in the hourCounts array.
The hoursCount array at right would print:
0:0
1:5
2:0
3:0
4:2
:
public void printHourlyCounts()
{
System.out.println("Hour: Count");
for( int hour = 0; hour < hourCounts.length; hour++)
{
System.out.println(hour + ": " + hourCounts[ hour ]);
}
}
Fixed size arrays can hold:
- primitive types (int, double, boolean) as seen above
- references to objects as seen below
Array define - The following defines tms as a TicketMachine array object at right, assuming the TicketMachine definition of Chapter 2):
TicketMachine [] tms; Array create and assign - The following creates a fixed size array of
3 TicketMachines and assigns the object reference to tms:
tms = new TicketMachine [ 3 ];
Object create and assign - The following creates 3 TicketMachines and assigns each to one of the indexed variables of the array:
tms [ 0 ] = new TicketMachine ( 40 );
tms [ 1 ] = new TicketMachine ( 50 );
tms [ 2 ] = new TicketMachine ( 60 );
Array use - The following calls the insertMoney(), emptyMachine() and printTicket() methods using TicketMachine numbered 2.
tms [ 2 ].insertMoney ( 70 );
tms [ 2 ].printTicket ( );
System.out.println( tms [ 2 ].emptyMachine( ) );
Exercise 12 - Array of objects In your head
- What ticket is printed in the previous example?
- What is printed by:
System.out.println( tms [ 2 ].emptyMachine( ) );
Exercise 13 - for loop In your head
- Complete the numberOfAccesses method below to count the total number of accesses recorded in the log file. Complete using a for loop iterating over the hourCounts array.
public int numberOfAccesses()
{
int total = 0;
// total each variable of hourCounts
return total;
}In BlueJ
- Add numberOfAccesses method to LogAnalyzer class and test.
Exercise 14 - for loop In your head
- Three TicketMachines below are:
- defined
- created
- money inserted
- emptied and totaled
TicketMachine t0, t1, t2;
t0 = new TicketMachine( 40 );
t1 = new TicketMachine( 50 );
t2 = new TicketMachine( 60 );
t0.insertMoney( 100 );
t1.insertMoney( 75 );
t2.insertMoney( 85 );
int sum = 0;
sum = sum + t0.emptyMachine();
sum = sum + t1.emptyMachine();
sum = sum + t2.emptyMachine();
- Complete the following to obtain exactly the same results as above but using a fixed size array and for-loop.
TicketMachine [ ] tms; tms = new TicketMachine[3];
tms [ 0 ] = new TicketMachine( 40 );
tms [ 1 ] = new TicketMachine( 50 );
tms [ 2 ] = new TicketMachine( 60 );
tms [ 0 ].insertMoney( 100 );
tms [ 1 ].insertMoney( 75 );
tms [ 2 ].insertMoney( 85 );
int sum = 0;:
:
Exercise 15 In BlueJ
- Open project chapter02/better-ticket-machine.
- Create the new class Subway.
- Copy the following for Subway class.
public class Subway
{
private TicketMachine [ ] tms;
public Subway()
{
}
public int totalPrice()
{
}
}
- In the Subway constructor, assign tms an array of 100 TicketMachine's.
- In the Subway constructor, use a for-loop to assign each variable of tms to a TicketMachine with price 50 cents:
- tms[ i ] = new TicketMachine(50)
- Complete totalPrice() method to return the total price of all 100 machines.
- Test the totalPrice() method.
- Add a method averagePrice() to compute the average price of a ticket.
Exercise 16 In your head
Differences between ArrayList and fixed size arrays of Strings
- Define:
- An ArrayList variable of type String named: people.
- A fixed size array variable of type String named: dow.
- Create (construct):
- people an ArrayList object of type String.
- dow a String array of 7 variables.
- Assign:
- people the String objects "Tom", "Dick" and "Harry".
- dow the String objects "Sunday", "Monday", etc.
- Access:
- Print all objects of people.
- Print all objects of dow.
- Access:
Exercise 17 In your head
Differences between ArrayList and fixed size arrays of TicketMachines
- Define:
- An ArrayList variable of type TicketMachine named: bus.
- A fixed size array variable of type TicketMachine named: plane.
- Create (construct):
- bus an ArrayList of type TicketMachine object.
- plane a TicketMachine array of 3 variables.
- Assign:
- bus the TicketMachine objects with price 50, 150, 200.
- plane the TicketMachine objects with price 50, 150, 200.
- Access. Use void insertMoney(int amount):
- Insert 25 cents into all objects of bus.
- Insert 25 cents into all objects of plane.
- Access. Use int getPrice():
- Find the highest price of all objects of bus.
- Find the highest price of all objects of plane.
- Access. Use int emptyMachine():
- Empty and total all objects of bus.
- Empty and total all all objects of plane.
Exercise 18 In your head
Differences between ArrayList and fixed size arrays of Sound
- Define:
- An ArrayList variable of Songs named: songs.
- A fixed size array variable of type Sound named: days.
- Create (construct):
- songs an ArrayList of Songs object.
- days a Sound array of 3 variables.
- Assign:
- songs the Sound objects:
new Sound("2U", "ICanSing.wav", 3);
new Sound("Elvis", "ICanMakeUSing.wav", 4);
new Sound("Rain", "Sleep.wav", 2);
.- days the Sound objects:
new Sound("Sunday", "Sunday.wav", 3);
new Sound("Monday", "Monday.wav", 4);
new Sound("Tuesday", "Tuesday.wav", 2);
- Access, using the Sound void playSound() method:
- Play all objects of songs.
- Play all objects of days.
- Access, using the Sound int getDuration() accessor method:
- Compute the total duration of songs.
- Compute the total duration of days.
- Access, using the Sound int getDuration() accessor method:
- Find the longest duration of all objects of songs.
- Find the longest duration of all objects of days.
- Access, using the Sound int getDuration() accessor method:
- Find the index of the longest duration of all objects of songs.
- Find the index of the longest duration of all objects of days.