Chapter 4:


C201 Home Page


Chapter 4
Grouping Objects 

powered by FreeFind

Modified: 


Overview

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.

4.1 Grouping objects in flexible-size collections

Many objects in life come in groups:

Some groups are fixed in size while others are flexible size. We need programming features for modeling both cases.

4.2 A personal notebook

Exercise 1 - NoteBook class

In BlueJ

  1. Open project chapter04\notebook1.
  2. Click View | Show Terminal
  3. In Terminal window click Options | Record method calls
  4. Create a NoteBook object.
    • Add two notes:
      1. "Buy bread"
      2. "Sell car"
    • Check the number of notes stored.
    • Show each note. The first note is numbered 0, the second 1, etc.

4.3 A first look at library classes

Examples:

Example packages:

4.3.1 An example using a library

 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:

ArrayList methods:

The ArrayList class supplies many useful methods, we will use four for now:

  1. add - adds an object to the ArrayList. Example:
    • notes.add("Take vacation");
  2. size - returns the number of objects in the ArrayList. Example (assuming 3 objects):
    • notes.size(); returns 3.
  3. get - returns the ith object in ArrayList. Example:
    • notes.get( 2 ); returns the 2nd object from ArrayList notes.
  4. remove - removes the ith object in the ArrayList. Example (assuming 3 objects):
    • notes.remove(1);

4.4 Object structures with collections

Exercise 2 - NoteBook methods

In BlueJ

  1. Inspect the NoteBook object.
    1. Click on the notes field and Inspect button.
      • What is the value of field size?
    2. What do you think is the value of: notes.size()
    3. Click on elementData and Inspect button.
      • What is the number of:
        • "Sell car"
        • "Buy bread"
  2. Call method:
    • showNote to show note number 1.
    • numberOfNotes.
  3. Store another note "11:30 mtg"
    • What is the number of this note?
    • What is the value of: notes.size()?
  4. In what order does ArrayList objects store objects?
  5. Update the object diagram at right by hand to include "11:30 mtg" note.

4.5 Numbering within collections

Examples:

Exercise 3 - Indexes
  1. What would be the index of the next note added?
  2. What is:
    • notes.get(1);
    • notes.get(0);
    • notes.get(5);
    • System.out.println( notes.get( 1 ) );

4.6 Removing an item from a collection

Exercise 4 - remove
  1. What is the index of "11:30 mtg" after:
    • notes.remove(1);

  2. What is the value now of:
    •  notes.size()

  3. Add the mutator method deleteNote that removes the ith index note from the notebook. Assume the ith note exists.

  4. 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.

4.7 Processing a whole collection

Exercise 5 - listNotes
  1. Which of the signatures would be most appropriate:
    1. public ArrayList listNotes()
    2. public void listNotes(int index)
    3. public int listNotes()
    4. public void listNotes()

  2. 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) );
       :

4.7.1 The while loop

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

  1. 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.

  2. Modify listNotes method to print the notes in reverse order.
    • Create an instance with 2 notes and call the listNotes method.

  3. 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.

4.7.2 Iterating over 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
  1. From the diagram at right, what is printed by:

    Iterator theIter = notes.iterator();

    System.out.println( theIter.next( ) );

  2. From the diagram at right, what is printed by:

    Iterator it = notes.iterator();

    System.out.println( it.hasNext( ) );

  3. 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( ) );

4.7.3 Index access versus iterators

4.7.3.1 Grouping objects complete example - a party

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

  1. Create a new project named Exercise 7.1
     
  2. Create a new class named Person
    • Copy and paste the Person class above.
       
  3. Create a new class named Party
    • Copy and paste the Party class above.
       
  4. 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 );
     

  5. Give the object diagram for Question 4.

4.9.3 Casting

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

  1. Use the object diagram for Exercise 7.1, Question 5 above.
     
  2. For the object diagram, what is:
    1. p1.printPerson();
    2. ((Person) guests.get(1))
    3. ((Person) guests.get(1)).printPerson();
    4. wedding.indexPrintParty();
    5. wedding.iteratorPrintParty();
       
  3. Write the Party method leave(int) that removes the Person at a specified index.
     
  4. Write the Party method to compute the average age.
    You will need to use the getAge() method for a Person.

4.10 Fixed size collections

 

Examples that produce the same result
int x0;
int x1;
int x2;

x0 = -3;
x1 = -5;
x2 = -4;

int sum = x0 + x1 + x2;

int x[ ] = new int [ 3 ];

x[ 0 ] = -3;
x[ 1 ] = -5;
x[ 2 ] = -4;
 


int sum = x[ 0 ] + x[ 1 ] + x[ 2 ];

String notes0 ;
String notes1 ;
String notes2 ;

notes0 = "Buy bread";
notes1 = "Sell car";
notes2 = "11:30 mtg";

String  notes[ ] = new String[3];

notes[ 0 ] = "Buy bread";
notes[ 1 ] = "Sell car";
notes[ 2 ] = "11:30 mtg";

ArrayList notes = new ArrayList( );

notes.add( 0 ) = "Buy bread";
notes.add( 1 ) = "Sell car";
notes.add( 2 ) = "11:30 mtg";

String notes[ ] = new String[3];

notes[ 0 ] = "Buy bread";
notes[ 1 ] = "Sell car";
notes[ 2 ] = "11:30 mtg";

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";

  1. From the diagram at right, what is the result:
    1. String s = notes[ 2 ];
    2. notes[ 1 ] = notes[ 0 ];
    3. notes[ 2 ] = "Take a break";
    4. notes[ 3 ] = "Broke";
    5. notes[ -1 ] = "Broke";

  2. From the diagram at right, what is printed by:

    int i = 2;

    while ( i >= 0 ) {
        System.out.println( i + notes[ i ] );
        i = i - 1;

  3. Define the object pages, an array 4 ints, see the figure at right.
  4. Initialize index 2 of pages to 15.
  5. Give the statements to print the figure at right.

 

 

 

4.10.a Declaring array variables

Examples:

4.10.b Creating array objects

Examples:

Exercise 9 - Arrays
  1. Write a declaration for an array variable people that can refer to an array of Person objects.
  2. Assign variable people an array of 30 Person objects.
  3. Write a declaration for an array variable vacant that can refer to an array of booleans.
  4. Assign variable vacant an array of 13 booleans.
  5. Write a declaration for an array variable dim that can refer to an array of ints.
  6. Assign dim an array of 12 ints.

4.10.c Using array objects

Examples:

Exercise 10 - Using Arrays
  1. Initialize each variable (i.e. index) of dim with the number of days in January, February, etc. for this year.
  2. Sum index 5, 6 and 7 of dim to variable summer.
  3. Print index 5, 6 and 7 of dim.

4.10.d The for-loop

Example that produce the same result:

ArrayList notes = new ArrayList( );

notes.add( 0 ) = "Buy bread";
notes.add( 1 ) = "Sell car";
notes.add( 2 ) = "11:30 mtg";

String notes[ ] = new String[3];

notes[ 0 ] = "Buy bread";
notes[ 1 ] = "Sell car";
notes[ 2 ] = "11:30 mtg";

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:

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
  1. Print all the integers from 12 to 3.
  2. Print all variables in array hourCounts in reverse order.
  3. Print all the variables in array dim.
  4. Print all the variables in array dim in reverse order.
  5. Total all the variables in array dim.
  6. Find smallest value in array dim.

4.10.1 A log-file analyzer

Web-servers log client visits to web pages.

Analyzing the log file can determine:

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
 }

4.10.2 Declaring array variables

4.10.3 Creating array objects

 

The following creates the array at right:

 private int[ ] hourCounts;
   public LogAnalyzer()
  {
       hourCounts = new int[24];
    }

4.10.4 Using array objects

4.10.5 Analyzing the log file

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]);
       }
 }

4.10.5.1 Arrays of objects

Fixed size arrays can hold:

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( ) ); ?

4.10.6 The for loop

Exercise 13 - for loop

In your head

  1. 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

  1. 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;

4.11 Summary




C201 Home Page


Please send any comments to: jfdoyle@ius.edu 
Copyright © 2001-2004 by cgranda@ius.edu . All rights reserved.