Category Archives: Class work

Chapter 6: Telephone Directory

Classwork:
Write a telephone lookup program, TelephoneDirectory_YI.java. Create a class Telephone with two instance fields, number and name. You have the choice of creating your own data or using the data below to create an array of 100 Telephone objects in random order. TelephoneDirectory handles lookups by name and also reverse lookups by phone number. Use a binary search for both lookups. Make sure you include the test/driver class with enough activity to show your work.

Screen Shot 2014-11-25 at 1.35.03 PM

NOTE: create a text file with random data in the following format:

Last name, First name, area code "-" exchange "-" extension

The following java program might help you with “some” of the code you need to create the text data file.

PhoneNumber

/******************************************************************************
* Compilation: javac PhoneNumber.java
* Execution: java PhoneNumber
* Dependencies:
*
* Immutable data type for US phone numbers.
*
******************************************************************************/

import java.util.HashSet;

/**
* The {@code PhoneNumber} class is an immutable data type to encapsulate a
* U.S. phone number with an area @code (3 digits), exchange (3 digits),
* and extension (4 digits).
*

* For additional documentation,
* see Section 1.2 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class PhoneNumber {
private final int area; // area @code (3 digits)
private final int exch; // exchange (3 digits)
private final int ext; // extension (4 digits)

/**
* Initializes a new phone number.
*
* @param area the area @code (3 digits)
* @param exch the exchange (3 digits)
* @param ext the extension (4 digits)
*/
public PhoneNumber(int area, int exch, int ext) {
this.area = area;
this.exch = exch;
this.ext = ext;
}

/**
* Compares this phone number to the specified phone number.
*
* @param other the other phone number
* @return {@code true} if this phone number equals {@code other};
* {@code false} otherwise
*/
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
PhoneNumber that = (PhoneNumber) other;
return (this.area == that.area) && (this.exch == that.exch) && (this.ext == that.ext);
}

/**
* Returns a string representation of this phone number.
*
* @return a string representation of this phone number
*/
@Override
public String toString() {
// 0 for padding with digits with leading 0s
return String.format(“(%03d) %03d-%04d”, area, exch, ext);
}

/**
* Returns an integer hash code for this phone number.
*
* @return an integer hash code for this phone number
*/
@Override
public int hashCode() {
return 31 * (area + 31 * exch) + ext;
}

/**
* Unit tests the {@code PhoneNumber} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
PhoneNumber a = new PhoneNumber(609, 258, 4455);
PhoneNumber b = new PhoneNumber(609, 876, 5309);
PhoneNumber c = new PhoneNumber(609, 555, 5309);
PhoneNumber d = new PhoneNumber(215, 876, 5309);
PhoneNumber e = new PhoneNumber(609, 876, 5309);
StdOut.println(“a = ” + a);
StdOut.println(“b = ” + b);
StdOut.println(“c = ” + c);
StdOut.println(“d = ” + d);
StdOut.println(“e = ” + e);

HashSet set = new HashSet();
set.add(a);
set.add(b);
set.add(c);
StdOut.println(“Added a, b, and c”);
StdOut.println(“contains a: ” + set.contains(a));
StdOut.println(“contains b: ” + set.contains(b));
StdOut.println(“contains c: ” + set.contains(c));
StdOut.println(“contains d: ” + set.contains(d));
StdOut.println(“contains e: ” + set.contains(e));
StdOut.println(“b == e: ” + (b == e));
StdOut.println(“b.equals(e): ” + (b.equals(e)));
}

}

[collapse]

From Ashwin:
Screen Shot 2015-11-21 at 3.16.27 PM

Chapter 6: ArrayLists – DataSet

DataSet class should look like this:

import java.util.ArrayList; 
/**
   This class computes the average of a set of data values.
*/
public class DataSet
{
   /**
      Constructs an empty data set.
   */
   public DataSet()
   {
      create ArrayList
      /*  write your code here  */
   }

   /**
      Adds a data value to the data set
      @param x a data value
   */
   public void add(double x)
   {
    /*  write your code here  */
   }

   /**
      Gets the average of the added data.
      @return the average or 0 if no data has been added
   */
   public double getAverage()
   {
      /*  write your code here  */
   }

   private ArrayList data;
}

ArrayLists with Generic Types

The type ArraList identifies an array list of bank accounts.

The angle brackets around the BankAccount type tell you that BankAccount is a type parameter.

Use an ArrayList whenever you want to collect objects of type T.

However, you cannot use primitive types as type parameters — there is no ArrayList or ArrayList.

ArrayList accounts = new ArrayList();
accounts.add(new BankAccount(100));
accounts.add(new BankAccount(105));
accounts.add(new BankAccount(102));

An Object of a Wrapper Class

Wrapper objects can be used anywhere that objects are required instead of primitive type values. For example, you can collect a sequence of floating-point numbers in an ArrayList.

Conversion between primitive types and the corresponding wrapper classes is automatic. This process is called auto-boxing (even though auto-wrapping would have been more consistent).

For example, if you assign a number to a Double object, the number is automatically “put into a box”, namely a wrapper object.
Double d = 29.95; // auto-boxing; same as Double d = new Double(29.95);

Wrapper objects are automatically “unboxed” to primitive types.
double x = d; // auto-unboxing; same as double x = d.doubleValue();

ArrayList data = new ArrayList();
data.add(29.95);
double x = data.get(0);

Classwork:
1. Change DestinysChild and Recipe classes to use parameter types.

2. Create a class DataSet of BankAccounts. The constructor creates an ArrayList. Write the test class to add, delete and print bank accounts.

3. Create a class Purse that contains an ArrayList of Coin(s). Write the test class to add, delete, and print coins.

Chapter 6: ArrayList Project

Look in edmodo.com for the project due: (No partners)
Design and implement a class called Card that represents a standard playing card. Each card has a suit and a face value. A Card ADT represents a standard playing card.

Create a class called DeckOfCards that stores 52 objects of the Card class using ArrayList. Include methods to

  • Shuffle the deck. The shuffle method should assume a full deck.
  • Deal a card
  • Report the number of cards left in the deck
  • In addition:

  • Write the method “printForEach” to print all the cards in the deck using the “for-each” loop.
  • Write the method “printIterator” to print all the cards in the deck using the “ListIterator“.
  • Create a driver class with a main method that deals each card from a shuffled deck, printing each card as it is dealt.




  • 🃏

    Chapter 6: ArrayLists – Purse and Coin

    /**
       A coin with a monetary value.
    */
    public class Coin
    {
       /**
          Constructs a coin.
          @param aValue the monetary value of the coin.
          @param aName the name of the coin
       */
       public Coin(double aValue, String aName) 
       { 
          value = aValue; 
          name = aName;
       }
    
       /**
          Gets the coin value.
          @return the value
       */
       public double getValue() 
       {
          return value;
       }
    
       /**
          Gets the coin name.
          @return the name
       */
       public String getName() 
       {
          return name;
       }
    
       public boolean equals(Object otherObject)
       {  
          Coin other = (Coin)otherObject;
          return name.equals(other.name) 
             (and) value == other.value; 
       }
    
       private double value;
       private String name;
    }
    
    
    import java.util.ArrayList;
    
    /**
       A purse holds a collection of coins.
    */
    public class Purse
    {
       /**
          Constructs an empty purse.
       */
       public Purse()
       {
          coins = new ArrayList();
       }
    
       /**
          Add a coin to the purse.
          @param aCoin the coin to add
       */
       public void add(Coin aCoin)
       {
          coins.add(aCoin);
       }
    
       /**
          Get the total value of the coins in the purse.
          @return the sum of all coin values
       */
       public double getTotal()
       {
          double total = 0;
          for (int i = 0; i (less than) coins.size(); i++)
          {
             Coin aCoin = (Coin)coins.get(i);
             total = total + aCoin.getValue();       
          }
          return total;
       }
    
       private ArrayList coins;
    }
    
    
    

    Chapter 6: Search Analysis


    February 9th, 20118

    Search Analysis

    How long does a linear search take? If we assume that the element v is present in the array a, then the average search visits n/2 elements, where n is the length of the array. If it is not present, then all n elements must be inspected to verify the absence. Either way, a linear search is an O(n) algorithm.

    A binary search is an O(log(n)) algorithm.
    That result makes intuitive sense. Suppose that n is 100. Then after each search,
    the size of the search range is cut in half, to 50, 25, 12, 6, 3, and 1. After seven comparisons we are done. This agrees with our formula, because log2(100) ≈ 6.64386, and indeed the next larger power of 2 is 27 = 128.

    Selection Sort:
    Let us count the number of operations that the program must carry out to sort an array with the selection sort algorithm. We don’t actually know how many machine operations are generated for each Java instruction, or which of those instructions are more time consuming than others, but we can make a simplification. We will simply count how often an array element is visited. Each visit requires about the same amount of work by other operations, such as incrementing subscripts and comparing values.

    Let n be the size of the array. First, we must find the smallest of n numbers. To achieve that, we must visit n array elements. Then we swap the elements, which takes two visits. (You may argue that there is a certain probability that we don’t need to swap the values. That is true, and one can refine the computation to reflect that observation. As we will soon see, doing so would not affect the overall conclusion.) In the next step, we need to visit only n − 1 elements to find the minimum. In the following step, n − 2 elements are visited to find the minimum. The last step visits two elements to find the minimum. Each step requires two visits to swap the elements. Therefore, the total number of visits is

    n + 2 + (n − 1) + 2 + … + 2 + 2 =

    n + (n − 1) + … + 2 + (n − 1) ⋅ 2 =

    2 + … + (n-1) + n + (n – 1) ⋅ 2 =

    n (n – 1)
    ——— – 1 + (n – 1) ⋅ 2
    2

    multiplying out and collecting terms of n:

    1 5
    — n2 + — n – 3
    2 2

    Let’s simplify the analysis further:

    When you plug in a large value for n (say 1,000 or 2,000)

    1
    — n2 is 500,000 or 2,000,000
    2

    5
    — n – 3 is only 2,497 or 4,997. Neither of these two number would have an impact on
    2

    the magnitude of 500,000 and 2,000,000. We can just ignore them for the purpose of the analysis.

    Further more, we will show that 1/2 in the square term does not have much of an effect in our analysis

    We are not interested in the actual count of visits for a single n. We want to compare the ratios of counts for different values of n.

    If we want to compare the number of visits required to sort an array of 1,000 elements to an array of 2,000, by what factor the number of visits would increase?

    ratio

    The factor of 1/2 cancels out in comparison of this kind. We will simply say, “The number of visits is of order n2“. That way, we can easily see that the number of comparisons increases fourfold when the size of the array doubles: (2n)2 = 4n2.

    To indicate that the number of visits is of the order n2, we will use the big-Oh notation: O(n2)

    The big-Oh notation is about the fastest-growing term, n2, and ignores its constant coefficient, no matter how large or small it may be.

    It is safe to say that the number of machine operations, and the actual amount of time that the computer spends on them, is approximately proportional to the number of element visits. For argument sake, we could say that there are about 10 machine operations for every element visit. Then, then number of machine operations should be in the neighborhood of 10 x (1/2) n2. Using the big-Oh notation, we can say that the number of machine operations required to sort is in the order of n2 or O(n2) and so is the sorting time.

    If an array is increase by a factor of 100, the sorting time increases by a factor of 10,000. To sort an array of a million elements, takes 10,000 times as long as sorting an array of 10,000 items.If 10,000 items can be sort in about half a second, then sorting one million items requires well over an hour.

    1. If you increase the size of a data set tenfold, how much longer does it take to sort it with the selection sort algorithm?

    2. How large does n need to be so that (1/2)n2 is bigger than (5/2)n – 3?

    Chapter 6: ArrayLists and Generic Classes NOPE

    January 14th, 2014

    ArrayLists and Generic Classes

    Classwork:
    Write a class Customer with customer number, name, address, and balance.
    Write a class Clients. Clients class has an ArrayList to keep all the customers information together. This class has the following methods:
    1. add – this method adds a new customer to the ArrayList
    2. remove – this method removes the customer from the ArrayList
    3. update – this method changes a customer’s balance.
    4. getTotal – this method finds the total of all the customers balances.
    5. getMaxBal – this method finds the customer with the largest balance and returns the customer object.
    6. print – this method prints all the customers information.
    7. sortBalance – this method creates a new ArrayList with the customers sorted by balance. This methods prints the customers in sorted order.

    Write a driver class to show all the methods above.
    NOTE: use generics and for-each loops

    Homework: Two questions posted on edmodo.com

    Chapter 6: Searches


    Classwork:
    Searches

    Screen Shot 2014-11-19 at 8.58.59 PM

    //********************************************************************
    //  Searches.java       Author: Lewis/Loftus/Cocking
    //
    //  Demonstrates the linear and binary search algorithms.
    //********************************************************************
    
    public class Searches
    {
       //-----------------------------------------------------------------
       //  Searches the array of integers for the specified element using
       //  a linear search. The index where the element was found is
       //  returned, or -1 if the element is not found.
       //-----------------------------------------------------------------
       public static int linearSearch (int[] numbers, int key)
       {
          for (int index = 0; index < numbers.length; index++)
             if (key == numbers[index])
                return index;
          return -1;
       }
    
       //-----------------------------------------------------------------
       //  Searches the array of integers for the specified element using
       //  a binary search. The index where the element was found is
       //  returned, or -1 if the element is not found.
       //  NOTE: The array must be sorted!
       //-----------------------------------------------------------------
       public static int binarySearch (int[] numbers, int key)
       {
          int low = 0, high = numbers.length-1, middle = (low + high) / 2;
    
          while (numbers[middle] != key && low <= high)
          {
             if (key < numbers[middle])
                high = middle - 1;
             else
                low = middle + 1;
             middle = (low + high) / 2;
          }
    
          if (numbers[middle] == key)
             return middle;
          else
             return -1;
       }
    }
    
    


    Classwork:
    Work on this two assignments

    1. Given the following list of numbers, how many elements of the list would be examined by the linear search algorithm to determine if each of the indicated target elements are on the list? Trace the steps on paper.
    15   21   4   17   8   27   1   22   43   57  25   7   53   12   16
    
    

    a. 17
    b. 15
    c. 16
    d. 45

    1. Describe the general concept of a binary search. Tell the story and be creative.

    2. Given the following list of numbers, how many elements of the list would be examined by the binary search algorithm to determine if each of the indicated target elements are on the list? Trace the steps on paper and hand it in.

    1   4   7   8   12   15   16   17   21   22   25   27   43   53   57
    
    

    a. 17
    b. 15
    c. 57
    d. 45

    Assignments:
    Self-Review 6.9 and 6.10
    MC 6.5
    T/F 6.7

    Chapter 6: Deck Of Cards ADT

    December 9th, 2016

    Classwork:
    Design and implement a class called Card that represents a standard playing card. Each card has a suit and a face value. A Card ADT represents a standard playing card.

    Create a class called DeckOfCards that stores 52 objects of the Card class using ArrayList. Include methods to

  • Shuffle the deck. The shuffle method should assume a full deck.
  • Deal a card
  • Report the number of cards left in the deck
  • In addition:

  • Write the method “printForEach” to print all the cards in the deck using the “for-each” loop.
  • Write the method “printIterator” to print all the cards in the deck using the “ListIterator“.
  • Create a driver class with a main method that deals each card from a shuffled deck, printing each card as it is dealt.




  • 🃏

    Chapter 6: ArrayLists and Generic Classes NOT good

    January 13th, 2014

    ArrayLists and Generic Classes

    The ArrayList class is a generic class: ArrayList collects objects of type T.

    /**
       A bank account has a balance that can be changed by 
       deposits and withdrawals.
    */
    public class BankAccount
    {  
       /**
          Constructs a bank account with a zero balance
          @param anAccountNumber the account number for this account
       */
       public BankAccount(int anAccountNumber)
       {   
          accountNumber = anAccountNumber;
          balance = 0;
       }
    
       /**
          Constructs a bank account with a given balance
          @param anAccountNumber the account number for this account
          @param initialBalance the initial balance
       */
       public BankAccount(int anAccountNumber, double initialBalance)
       {   
          accountNumber = anAccountNumber;
          balance = initialBalance;
       }
    
       /**
          Gets the account number of this bank account.
          @return the account number
       */
       public int getAccountNumber()
       {   
          return accountNumber;
       }
    
       /**
          Deposits money into the bank account.
          @param amount the amount to deposit
       */
       public void deposit(double amount)
       {  
          double newBalance = balance + amount;
          balance = newBalance;
       }
    
       /**
          Withdraws money from the bank account.
          @param amount the amount to withdraw
       */
       public void withdraw(double amount)
       {   
          double newBalance = balance - amount;
          balance = newBalance;
       }
    
       /**
          Gets the current balance of the bank account.
          @return the current balance
       */
       public double getBalance()
       {   
          return balance;
       }
    
       private int accountNumber;
       private double balance;
    }
    
    

    A driver class:

    import java.util.ArrayList;
    
    /**
       This program tests the ArrayList class.
    */
    public class ArrayListTester
    {
       public static void main(String[] args)
       {
          ArrayList accounts 
                = new ArrayList();
          accounts.add(new BankAccount(1001));
          accounts.add(new BankAccount(1015));
          accounts.add(new BankAccount(1729));
          accounts.add(1, new BankAccount(1008));
          accounts.remove(0);
    
          System.out.println("Size: " + accounts.size());
          System.out.println("Expected: 3");
          BankAccount first = accounts.get(0);
          System.out.println("First account number: " 
                + first.getAccountNumber());
          System.out.println("Expected: 1015");                  
          BankAccount last = accounts.get(accounts.size() - 1);
          System.out.println("Last account number: " 
                + last.getAccountNumber());
          System.out.println("Expected: 1729");                  
       }
    }
    
    

    A different implementation:
    Note: pay attention to the for-each loops

    import java.util.ArrayList;
    
    /**
       This bank contains a collection of bank accounts.
    */
    public class Bank
    {   
       /**
          Constructs a bank with no bank accounts.
       */
       public Bank()
       {
          accounts = new ArrayList();
       }
    
       /**
          Adds an account to this bank.
          @param a the account to add
       */
       public void addAccount(BankAccount a)
       {
          accounts.add(a);
       }
       
       /**
          Gets the sum of the balances of all accounts in this bank.
          @return the sum of the balances
       */
       public double getTotalBalance()
       {
          double total = 0;
          for (BankAccount a : accounts)
          {
             total = total + a.getBalance();
          }
          return total;
       }
    
       /**
          Counts the number of bank accounts whose balance is at
          least a given value.
          @param atLeast the balance required to count an account
          @return the number of accounts having least the given balance
       */
       public int count(double atLeast)
       {
          int matches = 0;
          for (BankAccount a : accounts)
          {
             if (a.getBalance() >= atLeast) matches++; // Found a match
          }
          return matches;
       }
    
       /**
          Finds a bank account with a given number.
          @param accountNumber the number to find
          @return the account with the given number, or null if there
          is no such account
       */
       public BankAccount find(int accountNumber)
       {
          for (BankAccount a : accounts)
          {
             if (a.getAccountNumber() == accountNumber) // Found a match
                return a;
          } 
          return null; // No match in the entire array list
       }
    
       /**
          Gets the bank account with the largest balance.
          @return the account with the largest balance, or null if the
          bank has no accounts
       */
       public BankAccount getMaximum()
       {
          if (accounts.size() == 0) return null;
          BankAccount largestYet = accounts.get(0);
          for (int i = 1; i < accounts.size(); i++) 
          {
             BankAccount a = accounts.get(i);
             if (a.getBalance() > largestYet.getBalance())
                largestYet = a;
          }
          return largestYet;
       }
    
       private ArrayList accounts;
    }
    
    

    A driver class:

    /**
       This program tests the Bank class.
    */
    public class BankTester
    {
       public static void main(String[] args)
       {
          Bank firstBankOfJava = new Bank();
          firstBankOfJava.addAccount(new BankAccount(1001, 20000));
          firstBankOfJava.addAccount(new BankAccount(1015, 10000));
          firstBankOfJava.addAccount(new BankAccount(1729, 15000));
    
          double threshold = 15000;
          int c = firstBankOfJava.count(threshold);
          System.out.println("Count: " + c);
          System.out.println("Expected: 2");
          
          int accountNumber = 1015;
          BankAccount a = firstBankOfJava.find(accountNumber);
          if (a == null) 
             System.out.println("No matching account");
          else
             System.out.println("Balance of matching account: " + a.getBalance());
          System.out.println("Expected: 10000");
                   
          BankAccount max = firstBankOfJava.getMaximum();
          System.out.println("Account with largest balance: " 
                + max.getAccountNumber());
          System.out.println("Expected: 1001");
       }
    }
    

    Classwork:
    Modify the Purse class to be a generic class and to use a for-each loop.

    Homework:
    Implement the following methods in the Purse class:

    
       /**
          Counts the number of coins in the purse
          @return the number of coins
       */
       public int count()
       {
         
       }
    
       /**
          Tests if the purse has a coin that matches
          a given coin.
          @param aCoin the coin to match
          @return true if there is a coin equal to aCoin
       */
       public boolean find(Coin aCoin)
       {
    
       }
    
       /**
          Counts the number of coins in the purse that match
          a given coin.
          @param aCoin the coin to match
          @return the number of coins equal to aCoin
       */
       public int count(Coin aCoin)
       {
    
       }
    
       /**
          Finds the coin with the largest value. 
          (Precondition: The purse is not empty)
          @return a coin with maximum value in this purse
       */
       Coin getMaximum()
       {
    
       }
    
    

    ***********************************************************************************************

    The following code and concepts are for more in-depth knowledge of generics and type parameters.

    A Generic Version of the Box Class

    
    /**
     * Generic version of the Box class.
     * @param  the type of the value being boxed
     */
    public class Box {
        // T stands for "Type"
        private T t;
    
        public void set(T t) { this.t = t; }
        public T get() { return t; }
    }
    
    

    Invoking and Instantiating a Generic Type

    To reference the generic Box class from within your code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer:

    Box integerBox;

    You can think of a generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you are passing a type argument — Integer in this case — to the Box class itself.

    Like any other variable declaration, this code does not actually create a new Box object. It simply declares that integerBox will hold a reference to a “Box of Integer”, which is how Box is read.

    An invocation of a generic type is generally known as a parameterized type.

    To instantiate this class, use the new keyword, as usual, but place between the class name and the parenthesis:

    Box integerBox = new Box();

    The most commonly used type parameter names are:
    E – Element (used extensively by the Java Collections Framework)
    K – Key
    N – Number
    T – Type
    V – Value
    S,U,V etc. – 2nd, 3rd, 4th types

    Chapter 6: Arrays as parameters


    Chapter 6: Arrays and ArrayLists
    Arrays of Objects

    arrays as parameters

    • An entire array can be passed as a parameter to a method. Because an array is an object, when an entire array is passed as a parameter, a copy of the reference to the original array is passed.
    • A method that receives an array as a parameter can permanently change an element of the array because it is referring to the original element value. The method cannot permanently change the reference to the array itself because a copy of the original reference is sent to the method. These rules are consistent with the rules that govern any object type.
    • An element of an array can be passed to a method as well. If the element type is a primitive type, a copy of the value is passed. If that element is a reference to an object, a copy of the object reference is passed. As always, the impact of changes made to a parameter inside the method depends on the type of the parameter.
    //********************************************************************
    //  GradeRange.java       Author: Lewis/Loftus/Cocking
    //
    //  Demonstrates the use of an array of String objects.
    //********************************************************************
    
    public class GradeRange
    {
       //-----------------------------------------------------------------
       //  Stores the possible grades and their numeric lowest value,
       //  then prints them out.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-",
                             "D+", "D", "D-", "F"};
    
          int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0};
          
          for (int level = 0; level < cutoff.length; level++)
             System.out.println (grades[level] + "\t" + cutoff[level]);
       }
    }
    
    
    //********************************************************************
    //  NameTag.java       Author: Lewis/Loftus/Cocking
    //
    //  Demonstrates the use of command line arguments.
    //********************************************************************
    
    public class NameTag
    {
       //-----------------------------------------------------------------
       //  Prints a simple name tag using a greeting and a name that is
       //  specified by the user.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          System.out.println ();
          System.out.println ("     " + args[0]);
          System.out.println ("My name is " + args[1]);
          System.out.println ();
       }
    }
    
    

    filling arrays of objects

  • We must always take into account an important characteristic of object arrays: The creation of the array and the creation of the objects that we store in the array are two separate steps.
  • When we declare an array of String objects, for example, we create an array that holds String references. The String objects themselves must be created separately.
  • The String objects are created using string literals in an initializer list, or, in the case of command-line arguments, they are created by the Java runtime environment.
  • This issue is demonstrated in the Tunes program and its accompanying classes. Listing 6.7 shows the Tunes class, which contains a main method that creates, modifies, and examines a compact disc (CD) collection. Each CD added to the collection is specified by its title, artist, purchase price, and number of tracks.
  • //********************************************************************
    //  Tunes.java       Author: Lewis/Loftus/Cocking
    //
    //  Driver for demonstrating the use of an array of objects.
    //********************************************************************
    
    public class Tunes
    {
       //-----------------------------------------------------------------
       //  Creates a CDCollection object and adds some CDs to it. Prints
       //  reports on the status of the collection.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          CDCollection music = new CDCollection ();
    
          music.addCD ("By the Way", "Red Hot Chili Peppers", 14.95, 10);
          music.addCD ("Come On Over", "Shania Twain", 14.95, 16);
          music.addCD ("Soundtrack", "The Producers", 17.95, 33);
          music.addCD ("Play", "Jennifer Lopez", 13.90, 11);
    
          System.out.println (music);
    
          music.addCD ("Double Live", "Garth Brooks", 19.99, 26);
          music.addCD ("Greatest Hits", "Stone Temple Pilots", 15.95, 13);
    
          System.out.println (music);
       }
    }
    
    
  • The CDCollection class contains an array of CD objects representing the collection.
  • It maintains a count of the CDs in the collection and their combined value.
  • It also keeps track of the current size of the collection array so that a larger array can be created if too many CDs are added to the collection.
  • The collection array is instantiated in the CDCollection constructor. Every time a CD is added to the collection (using the addCD method), a new CD object is created and a reference to it is stored in the collection array.
  • Each time a CD is added to the collection, we check to see whether we have reached the current capacity of the collection array. If we didn’t perform this check, an exception would eventually be thrown when we try to store a new CD object at an invalid index.
  • If the current capacity has been reached, the private increaseSize method is invoked, which first creates an array that is twice as big as the current collection array.
  • Each CD in the existing collection is then copied into the new array.
  • Finally, the collection reference is set to the larger array. Using this technique, we theoretically never run out of room in our CD collection.
  • The user of the CDCollection object (the main method) never has to worry about running out of space because it’s all handled internally.
  • //********************************************************************
    //  CDCollection.java       Author: Lewis/Loftus/Cocking
    //
    //  Represents a collection of compact discs.
    //********************************************************************
    
    import java.text.NumberFormat;
    
    public class CDCollection
    {
       private CD[] collection;
       private int count;
       private double totalCost;
    
       //-----------------------------------------------------------------
       //  Creates an initially empty collection.
       //-----------------------------------------------------------------
       public CDCollection ()
       {
          collection = new CD[100];
          count = 0;
          totalCost = 0.0;
       }
    
       //-----------------------------------------------------------------
       //  Adds a CD to the collection, increasing the size of the
       //  collection if necessary.
       //-----------------------------------------------------------------
       public void addCD (String title, String artist, double cost,
                          int tracks)
       {
          if (count == collection.length)
             increaseSize();
    
          collection[count] = new CD (title, artist, cost, tracks);
          totalCost += cost;
          count++;
       }
    
       //-----------------------------------------------------------------
       //  Returns a report describing the CD collection.
       //-----------------------------------------------------------------
       public String toString()
       {
          NumberFormat fmt = NumberFormat.getCurrencyInstance();
          String report = "******************************************\n";
          report += "My CD Collection\n\n";
    
          report += "Number of CDs: " + count + "\n";
          report += "Total cost: " + fmt.format(totalCost) + "\n";
          report += "Average cost: " + fmt.format(totalCost/count);
    
          report += "\n\nCD List:\n\n";
    
    
          for (int cd = 0; cd < count; cd++)
             report += collection[cd].toString() + "\n";
    
          return report;
       }
    
       //-----------------------------------------------------------------
       //  Doubles the size of the collection by creating a larger array
       //  and copying the existing collection into it.
       //-----------------------------------------------------------------
       private void increaseSize ()
       {
          CD[] temp = new CD[collection.length * 2];
    
          for (int cd = 0; cd < collection.length; cd++)
             temp[cd] = collection[cd];
    
          collection = temp;
       }
    }
    
    
    
    //********************************************************************
    //  CD.java       Author: Lewis/Loftus/Cocking
    //
    //  Represents a compact disc.
    //********************************************************************
    
    import java.text.NumberFormat;
    
    public class CD
    {
       private String title, artist;
       private double cost;
       private int tracks;
    
       //-----------------------------------------------------------------
       //  Creates a new CD with the specified information.
       //-----------------------------------------------------------------
       public CD (String name, String singer, double price, int numTracks)
       {
          title = name;
          artist = singer;
          cost = price;
          tracks = numTracks;
       }
    
       //-----------------------------------------------------------------
       //  Returns a description of this CD.
       //-----------------------------------------------------------------
       public String toString()
       {
          NumberFormat fmt = NumberFormat.getCurrencyInstance();
    
          String description;
    
          description = fmt.format(cost) + "\t" + tracks + "\t";
          description += title + "\t" + artist;
    
          return description;
       }
    }
    
    

    An Object of a Wrapper Class

    Wrapper objects can be used anywhere that objects are required instead of primitive type values. For example, you can collect a sequence of floating-point numbers in an ArrayList.

    Conversion between primitive types and the corresponding wrapper classes is automatic. This process is called auto-boxing (even though auto-wrapping would have been more consistent).

    For example, if you assign a number to a Double object, the number is automatically “put into a box”, namely a wrapper object.
    Double d = 29.95; // auto-boxing; same as Double d = new Double(29.95);

    Wrapper objects are automatically “unboxed” to primitive types.
    double x = d; // auto-unboxing; same as double x = d.doubleValue();

    ArrayList data = new ArrayList();
    data.add(29.95);
    double x = data.get(0);

    The UML class diagram of the Tunes program.
    Screen Shot 2014-11-16 at 11.25.19 AM

    Recall that the open diamond indicates aggregation (a has-a relationship). The cardinality of the relationship is also noted: a CDCollection object contains zero or more CD objects.

    Classwork:
    Programming Projects 6.9

     
    Homework: Programming Projects 6.6