Chapter 4:
![]()
Chapter 4 |
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.
- Add 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 notes;
public NoteBook()
{
notes = new ArrayList();
}
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 notes; - Define field notes as type ArrayList class.
- notes = new ArrayList() - 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);
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: 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 is the number of this note?
- What is the value of: notes.size()?
- In what order does ArrayList objects store objects?
- Update the object diagram at right by hand to include "11:30 mtg" note.

| 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
- What would be the index of the next note added?
- What is:
- notes.get(1);
- notes.get(0);
- notes.get(5);
- System.out.println( notes.get( 1 ) );
Exercise 4 - remove
- What is the index of "11:30 mtg" after:
- notes.remove(1);
- What is the value now of:
- notes.size()
- Add the mutator method deleteNote that removes the ith index note from the notebook. Assume the ith note exists.
- 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 - listNotes
- Which of the signatures would be most appropriate:
- public ArrayList listNotes()
- public void listNotes(int index)
- public int listNotes()
- public void listNotes()
- Index 0 holds the first note, index 1 the second, etc. What is wrong with the following as the body for listNotes method?
System.out.println( notes.get(0) );
System.out.println( notes.get(1) );
System.out.println( notes.get(2) );
:
| 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;
i = i + 1;
i = i + 1;
i = i + 1;
i = i + 1;int i = 0;
while ( i <= 4 ) {
i = i + 1;
}int i = 4;
i = i - 1;
i = i - 1;
i = i - 1;
i = i - 1;int i = 4;
while ( i > 0 ) {
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 );
}System.out.println( notes.get(0) );
System.out.println( notes.get(1) );
System.out.println( notes.get(2) );
System.out.println( notes.get(3) );
System.out.println( notes.get(4) );
System.out.println( notes.get(5) );int i = 0;
while ( i <= 5 ) {
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 - listNotes
- Which of the above would be most appropriate for the body of listNotes?
In BlueJ
- Copy and paste the appropriate signature and body for listNotes method into NoteBook class.
- Create an instance with 2 notes and call the listNotes method.
- Modify listNotes method to print the notes in reverse order.
- Create an instance with 2 notes and call the listNotes method.
- Modify deleteNote to print out an error message if the note number parameter is not valid.
Infinite loops
Looping 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()
{
while( true )
System.out.println( "Forever...");
}
- Test by 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.
- BlueJ often becomes somewhat unstable. Suggest closing and restarting BlueJ.
| iterator - An object that provides the ability to iterate over every element in a collection. |
Example that produce the same result:
System.out.println( notes.get(0) );
System.out.println( notes.get(1) );
System.out.println( notes.get(2) );Iterator 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 i = notes.iterator();
while ( i.hasNext() ) {
System.out.println( i.next() );
}
Exercise 7 - Iterators
- From the diagram at right, what is printed by:
Iterator theIter = notes.iterator();
System.out.println( theIter.next( ) );- From the diagram at right, what is printed by:
Iterator it = notes.iterator();
System.out.println( it.hasNext( ) );- What is printed by:
Iterator 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 newAge, String newName) {
age=newAge;
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 guests;
public Party() {
guests = new ArrayList();
}
public void arrive( Person partier ) {
guests.add( partier );
}
public void indexPrintParty() {
int i = 0;
while (i < guests.size())
{
((Person) guests.get(i)).printPerson();
i = i + 1;
}
}
public void iteratorPrintParty() {
Iterator git = guests.iterator();
while ( git.hasNext() )
((Person) git.next()).printPerson();
}
}
Exercise 7.1 - Example 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(43, "George");
Person p1 = new Person(29, "Sally");Party wedding = new Party();
wedding.arrive( p0 );
wedding.arrive( p1 );
- Give the object diagram for Question 4.
A collection can hold any type of an object. It is therefore necessary to give the compiler information as to the type of object retrieved from the collection by casting the object to a specific type.
For example, in the above Party class, the guests ArrayList contains Person objects. The following method call fails because the compiler does not know the class of the object retrieved from the guests ArrayList:
(guests.get(1)).printPerson(); The following method call succeeds because the compiler does know the class of the object retrieved from the guests ArrayList:
((Person) guests.get(1)).printPerson(); Generally, the object retrieved must be cast to the class of the method.
Exercise 7.2 - Casting In BlueJ
- Use the object diagram for Exercise 7.1, Question 5 above.
- For the object diagram, what is:
- p1.printPerson();
- ((Person) guests.get(1))
- ((Person) guests.get(1)).printPerson();
- wedding.indexPrintParty();
- wedding.iteratorPrintParty();
- Write the Party method leave(int) that removes the Person at a specified index.
- Write the Party method to compute the average age.
You will need to use the getAge() method for a Person.
| 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( 0 ) = "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. |
Example that produce the same result:
ArrayList notes = new ArrayList( ); notes.add( 0 ) = "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 < 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 hourCounts:
int largest;
largest = hourCounts[0];
for ( int i = 0; i < 24; i++)
if ( hourCounts[ i ] > largest )
largest = hourCounts[ 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 dim.
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
2002 5 01 00 19
2002 5 01 01 27
2002 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]++;
}
}
public void printHourlyCounts()
{
System.out.println("Hr: Count");
for(int hour = 0; hour < hourCounts.length; hour++)
{
System.out.println(hour + ": " + hourCounts[hour]);
}
}
public void printData()
{
reader.printData();
}
} LogAnalyzer - 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]++;printHourlyCounts - Prints each of the
24 variables in the hourCounts array.
The hoursCount array above
would print:
0:0
1:5
2:0
3:0
4:2
public class LogAnalyzer
{
private int hourCounts;
private LogFileReader reader;
Constructor and methods omitted
}

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("Hr: 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):
private tms[ ] TicketMachine; 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 [ ] t;
t [ 0 ] = new TicketMachine( 40 );
t [ 1 ] = new TicketMachine( 50 );
t [ 2 ] = new TicketMachine( 60 );
t [ 0 ].insertMoney( 100 );
t [ 1 ].insertMoney( 75 );
t [ 2 ].insertMoney( 85 );
int sum = 0;
Please send any comments to: jfdoyle@ius.edu
Copyright ©
2001-2004 by cgranda@ius.edu . All
rights reserved.