JMU
Type-Safe/Parameterized Collections
in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
When These Limitations Arise
Beyond Arrays
UML
The java.util.List Interface
The java.util.Map Interface
The java.util.Map Interface (cont.)
Realizations of these Interfaces
Realizations of these Interfaces (cont.)
Type-Safety and Collections
A Type-Safe ArrayList
A Type-Safe ArrayList (cont.)

An Example

javaexamples/collections/typesafe/TextFormatter.java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * A simple class for formatting text messages.
 *
 * This class illustrates the use of the ArrayList
 * class.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 2.0 (Using a type-safe parameterized class)
 */
public class TextFormatter
{

    /**
     * The entry point of the program
     *
     * @param args  The command-line arguments
     */
    public static void main(String[] args)
    {
       int           displayWidth, i, width;
       Scanner       scanner;       
       String        word;
       List<String>  message;          // v2.0


       // Initialization
       displayWidth = 20;
       scanner      = new Scanner(System.in);       

       // Construct a new ArrayList
       message = new ArrayList<String>();  // v2.0


       // Prompt the user to enter the message
       // one word at a time
       do 
       {
          System.out.print("Next word: ");
          word = scanner.nextLine();
          message.add(message.size(), word);
       } 
       while (!word.equals(""));


       System.out.print("\n\n\n");

       // Format the message so that it fits in
       // a fixed-width display
       width = displayWidth;
       for (i=0; i < message.size(); i++) 
       {
          word = message.get(i);         // v2.0

          if (width+word.length()+1 > displayWidth) 
          {
             width = word.length();
             System.out.print("\n");
             System.out.print(word);
          } 
          else 
          {
             width = width + word.length() + 1;
             System.out.print(" "+word+" ");
          }
       }
    }
}
        
A Type-Safe HashMap
A Type-Safe HashMap (cont.)

An Example

javaexamples/collections/typesafe/CallerID.java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * A simple class for performing a "Caller ID"
 * (i.e., look up a person's name given their
 * phone number)
 *
 * This class illustrates the use of the HashMap
 * class.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 2.0 (Using a type-safe parameterized class)
 */
public class CallerID
{

    /**
     * The entry point of the program
     *
     * @param args  The command-line arguments
     */
    public static void main(String[] args)
    {
        Scanner                    scanner;        
        Map<String, String>        names;       // v2.0
        String                     id, number;

        scanner = new Scanner(System.in);        

        // Construct a new HashMap
        names = new HashMap<String, String>();     // v2.0


        // Fill the HashMap
        names.put("540-568-1671","Bernstein, D.");
        names.put("540-568-2773","Fox, C.");
        names.put("540-568-6288","Grove, R.");
        names.put("540-568-2774","Harris, A.");
        names.put("540-568-8771","Harris, N.");
        names.put("540-568-8745","Heydari, N.");
        names.put("540-568-2772","Lane, M.");
        names.put("540-568-2727","Marchal, J.");
        names.put("540-568-2775","Mata-Toledo, R.");
        names.put("540-568-2777","Norton, M.");


        // Prompt the user to enter a phone number
        // and then display the appropriate name
        do 
        {
           System.out.print("Phone Number: ");
           number = scanner.nextLine();
           
           id = names.get(number);          // v2.0

           if (id != null) System.out.printf("%s\n", id);
        } 
        while (!number.equals(""));
    }

}
        
Using the Value as the Key in a Collection
Java's Parameterized Collections in UML

The parameters for the class are listed (in order) in the dotted rectangle and are used as types elsewhere.

images/collections_java_parameterized.gif

Note that parameters are not explicitly included in constructors. Note also that bound parameters are included in arguments or return types (e.g., the keySet() method returns a Set of K so it is written as Set<K>). Note finally that Map is not "officially" a Collection (for reasons we will discuss later).

An Important Observation
Wrapper Classes
Boxing and Unboxing
Boxing and Unboxing (cont.)

An Example

javaexamples/collections/typesafe/StatisticsCalculator.java
import java.io.*;
import java.util.*;

/**
 * A simple calculator that can be used to calculate
 * descriptive statistics from a sample contained in a file
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 2.0 (Using type-safe generics)
 */
public class StatisticsCalculator
{
    private List<Double>        values;   // v2.0
    

    /**
     * Explicit Value Constructor
     *
     * @param name   The name of the file containing the sample
     */
    public StatisticsCalculator(String name) throws IOException
    {
       double        value;       
       Scanner       in;
    

       // Initialize the ArrayList
       values = new ArrayList<Double>();
       
       // Read the data
       in = new Scanner(new File(name));
       while (in.hasNext())
       {
          value = in.nextDouble();
          values.add(value);          // v2.0 (boxing)
       }
    }
    

    /**
     * Calculates the mean of a sample
     *
     * @return    The mean
     */
    public double mean()
    {
       double        total, value;
       

       total = 0.0;
       
       for (int i=0; i<values.size(); i++)
       {
          value =  values.get(i);    // v2.0 (unboxing)
          total += value;          
       }
       
       return total/((double)values.size());
    }
    

    /**
     * Calculates the sum of the squared residuals [i.e., the
     * sum of (x_i - xbar)^2 ]
     */
    private double ssr()
    {
       double        mean, sum, value;

       mean  = mean();
       
       sum   = 0.0;
       
       for (int i=0; i<values.size(); i++)
       {
          value = values.get(i);     // v2.0  (unboxing)
          sum   += Math.pow((value - mean), 2);
       }
       
       return sum;
    }


    /**
     * Calculates the (biased) variance of a sample
     *
     * @return  The (biased) variance
     */
    public double variance()
    {
       return (1.0/(double)(values.size())) * ssr();       
    }
    
}
        
Other Wrapper Classes
Collections of Collections
Collections of Collections (cont.)

Using Parameterized Collections

javaexamples/collections/typesafe/Courses.java
import java.util.*;


/**
 * An example that uses a parameterized collection of a parameterized
 * collection
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Courses
{
    /**
     * The entry point
     *
     * @param args    The command line arguments (ignored)
     */
    public static void main(String[] args)
    {
       Map<String, List<String>>    offerings;
       List<String>                 course;
       

       offerings = new HashMap<String, List<String>>();


       
       // Sections of CS139
       course = new ArrayList<String>();
       course.add("Harris, J.A.");
       course.add("Harris, N.L.");
       
       offerings.put("CS139", course);


       
       // Sections of CS159
       course = new ArrayList<String>();
       course.add("Bernstein");
       course.add("Harris, N.L.");
       
       offerings.put("CS159", course);
       

       
       // Sections of CS446
       course = new ArrayList<String>();
       course.add("Bernstein");
       course.add("Fox");
       
       offerings.put("CS446", course);
    }
    
}
        
Type-Safe Collections and Specialization
Type-Safe Collections and Specialization (cont.)

An Example

javaexamples/collections/typesafe/SecurityDriver.java (Fragment: 1)
       ArrayList<SecurityQuotation>  quotes;
       

       quotes = new ArrayList<SecurityQuotation>();
       quotes.add(new StockQuotation());
       quotes.add(new FutureQuotation());
        
Type-Safe Collections and Specialization (cont.)
Type-Safe Collections and Specialization (cont.)

The Following will Result in a Compile-Time Error

javaexamples/collections/typesafe/SecurityDriver.java (Fragment: 2)
       ArrayList<SecurityQuotation>  securities;
       ArrayList<StockQuotation>     stocks;
       

       stocks = new ArrayList<StockQuotation>();

       // This assignment involves incompatible types
       securities = stocks;
        
Type-Safe Collections and Specialization (cont.)
Type-Safe Collections and Specialization (cont.)

Using Wildcards

javaexamples/collections/typesafe/SecurityDriver.java (Fragment: 3)
       ArrayList<? extends SecurityQuotation>  nyse;
       ArrayList<StockQuotation>               temp;
       

       temp = new ArrayList<StockQuotation>();

       nyse = temp;