- Forward


Type-Safe/Parameterized Collections
in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Review
Back SMYC Forward
  • An Array:
    • A fixed-size "group" of homogeneous objects each of which is identified by an integer index
  • Limitations of Arrays:
    • Fixed size
    • Must be indexed by an integer
When These Limitations Arise
Back SMYC Forward
  • Fixed Size:
    • When we don't know even the maximum number of elements in the collection beforehand
  • Integer Index:
    • When the indices aren't numbers (e.g., names)
    • When the "important" integers are sparse (e.g., phone numbers)
Beyond Arrays
Back SMYC Forward
  • Collection:
    • An object that "groups" multiple elements into a single unit
  • Examples in Java:
    • List java.util.List
    • Map java.util.Map
UML
Back SMYC Forward
  • Aggregation:
    • An object of class A "has-an" object of class B if B is a part of A.
  • Obvious Applications to Collections:
    • images/aggregation-collection.gif
  • Less Obvious Applications:
    • images/aggregation-university.gif
The java.util.List Interface
Back SMYC Forward
  • Purpose:
    • A "growable" collection with an integer index
  • Important Methods:
    • void add(int index, E element)
    • E get(int index)
    • E set(int index, E element)
    • int size()
The java.util.Map Interface
Back SMYC Forward
  • Purpose:
    • A "growable" collection that can use any Object as an index/key
  • Important Methods:
    • V get(K key)
    • V put(K key, V value)
    • int size()
The java.util.Map Interface (cont.)
Back SMYC Forward
  • An Observation:
    • It must be possible to uniquely identify an Object (since it can be used as the key in a Map)
  • Some Internals:
    • Each Object has a hashCode() method that can be used for this purpose (which can be based on the object's address, but needn't be)
Realizations of these Interfaces
Back SMYC Forward
  • List:
    • ArrayList java.util.ArrayList
    • LinkedList java.util.LinkedList
  • Map:
    • HashMap java.util.HashMap
    • TreeMap java.util.TreeMap
Realizations of these Interfaces (cont.)
Back SMYC Forward
  • What Are the Differences?
    • The data structures used (i.e., the way memory is organized)
    • The algorithms used
  • Can You Be More Specific?
    • If you want to know more, take CS240 (Data Structures and Algorithms)
Type-Safety and Collections
Back SMYC Forward
  • Elements in a Collection:
    • In Java, one can put Object objects in a collection
    • Effectively, this means that you can put any reference type in a collection
  • A Shortcoming of this Approach:
    • You are forced to cast the Object to the appropriate type when you retrieve it
    • You may cast it incorrectly and this mistake will only be caught at run-time
  • Overcoming this Shortcoming:
    • Use parameterized classes/interfaces
A Type-Safe ArrayList
Back SMYC Forward
  • The Raw ArrayList Class:
    • Contains Object objects
    • An Example:
      List a; a = new ArrayList();
  • Parameterizing an ArrayList java.util.ArrayList :
    • Contains objects of a specified type
    • An Example:
      List<String> a; a = new ArrayList<String>();
A Type-Safe ArrayList (cont.)
Back SMYC Forward

An Example

javaexamples/collections/typesafe/TextFormatter.java
 
A Type-Safe HashMap
Back SMYC Forward
  • The Raw HashMap Class:
    • Uses Object objects as both the key and the value
    • An Example:
      Map h; h = new HashMap();
  • Parameterizing a HashMap java.util.HashMap :
    • Uses keys and values with specified types
    • An Example:
      Map<String, Robot> h; h = new HashMap<String, Robot>();
A Type-Safe HashMap (cont.)
Back SMYC Forward

An Example

javaexamples/collections/typesafe/CallerID.java
 
Using the Value as the Key in a Collection
Back SMYC Forward
  • The Issue:
    • Sometimes the key and the value are the same
  • Examples:
    • A "paint" application in which you add a bunch of different shapes to the canvas
    • A course-requirements application that needs to keep track of the courses you've taken
  • What To Do?
    • You could use a Map but it is better (i.e., clearer) to use a Set java.util.Set (like the HashSet java.util.HashSet )
Java's Parameterized Collections in UML
Back SMYC Forward

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
Back SMYC Forward
  • Parameters of add() (in List) and put() (in Map):
    • Must be an (extension of) Object
  • Implication:
    • A List and a Map can only contain class types
    • They can't contain an int, double, etc...
Wrapper Classes
Back SMYC Forward
  • Integer:
    • Deprecated Constructor: Integer(int value)
    • Factory: Integer.valueOf(int value)
    • Accessor: int intValue()
  • Double:
    • Deprecated Constructor: Double(double value)
    • Factory: Double.valueOf(double value)
    • Accessor: double doubleValue()
Boxing and Unboxing
Back SMYC Forward
  • Some Observations:
    • Wrapper classes are inconvenient
    • It seems like the process could be handled by the compiler
  • The Solution:
    • The compiler will automatically box (i.e., wrap) and unbox (unwrap) values when you use parameterized collections
Boxing and Unboxing (cont.)
Back SMYC Forward

An Example

javaexamples/collections/typesafe/StatisticsCalculator.java
 
Other Wrapper Classes
Back SMYC Forward
  • OptionalInt and OptionalDouble:
    • May or may not contain a value
  • Methods:
    • boolean isPresent()
    • int orElse(int default) and double orElse(double default) return the value if present and the default otherwise
Collections of Collections
Back SMYC Forward
  • An Example:
    • Map offerings; List cs139, cs159; offerings = new HashMap(); cs139 = new ArrayList(); cs139.add("Harris, J.A."); cs139.add("Harris, N.L."); offerings.put("CS139", cs139); cs159 = new ArrayList(); cs159.add("Bernstein"); cs159.add("Harris, N.L."); offerings.put("CS159", cs159);
  • An Observation:
    • This is not type safe
Collections of Collections (cont.)
Back SMYC Forward

Using Parameterized Collections

javaexamples/collections/typesafe/Courses.java
 
Type-Safe Collections and Specialization
Back SMYC Forward
  • Recall:
    • When we discussed specialization we considered an example in which there was an (abstract) SecurityQuotation class and two subclasses, StockQuotation and FutureQuotation
  • Two Questions:
    • Should we be able to create a type-safe collection (e.g., an ArrayList) that contains children of both types?
    • Can we (in Java)?
Type-Safe Collections and Specialization (cont.)
Back SMYC Forward

An Example

javaexamples/collections/typesafe/SecurityDriver.java (Fragment: 1)
 
Type-Safe Collections and Specialization (cont.)
Back SMYC Forward
  • Recall:
    • We can assign a StockQuotation object to a variable that is declared to be a SecurityQuotation (because a StockQuotation "is a" SecurityQuotation)
  • A Question:
    • Can we assign an ArrayList<StockQuotation> to a variable of type ArrayList<SecurityQuotation>?
Type-Safe Collections and Specialization (cont.)
Back SMYC Forward

The Following will Result in a Compile-Time Error

javaexamples/collections/typesafe/SecurityDriver.java (Fragment: 2)
 
Type-Safe Collections and Specialization (cont.)
Back SMYC Forward
  • Another Part of the Java Lexicon:
    • The ? is called the wildcard character
  • Java Syntax for Unbounded Wildcards:
    • Collection<?> variable
  • Java Syntax for Bounded Wildcards:
    • Collection<? extends Parent> variable
Type-Safe Collections and Specialization (cont.)
Back SMYC Forward

Using Wildcards

javaexamples/collections/typesafe/SecurityDriver.java (Fragment: 3)
 
There's Always More to Learn
Back -