Big Java 6

Chapter 18 – Generic Classes

Chapter Goals

generic food

Generic Classes and Type Parameters

Type Parameter

Type Parameters

Type Parameters Increase Safety

Self Check 18.1

The standard library provides a class HashMap<K, V> with key type K and value type V. Declare a hash map that maps strings to integers.

Self Check 18.2

The binary search tree class in Chapter 17 is an example of generic programming because you can use it with any classes that implement the Comparable interface. Does it achieve genericity through inheritance or type parameters?

Self Check 18.3

Does the following code contain an error? If so, is it a compile-time or run-time error?
ArrayList<Integer> a = new ArrayList<>();
String s = a.get(0);

Self Check 18.4

Does the following code contain an error? If so, is it a compile-time or run-time error?
ArrayList<Double> a = new ArrayList<>();
a.add(3);

Self Check 18.5

Does the following code contain an error? If so, is it a compile-time or run-time error?
LinkedList a = new LinkedList();
a.addFirst("3.14");
double x = (Double) a.removeFirst();

Implementing Generic Classes

Implementing Generic Types

Class Pair

public class Pair<T, S>
{
   private T first;
   private S second;
   
   public Pair(T firstElement, S secondElement)
   {
      first = firstElement; 
      second = secondElement;
   }
   public T getFirst() { return first; }
   public S getSecond() { return second; } 
}

Syntax 18.1 Declaring a Generic Class

syntax of a generic class

section_2/Pair.java

Your browser does not support the <object> tag.

section_2/PairDemo.java

Your browser does not support the <object> tag. Program Run:

Self Check 18.6

How would you use the generic Pair class to construct a pair of strings "Hello" and "World"?

Self Check 18.7

How would you use the generic Pair class to construct a pair containing "Hello" and 1729?

Self Check 18.8

What is the difference between an ArrayList<Pair<String, Integer>> and a Pair<ArrayList<String>, Integer>?

Self Check 18.9

Write a method roots with a Double parameter variable x that returns both the positive and negative square root of x if x ≥ 0 or null otherwise.

Self Check 18.10

How would you implement a class Triple that collects three values of arbitrary types?

Generic Methods

Generic Methods

Generic Methods

Generic Methods

Syntax 18.2 Declaring a Generic Method

syntax of generic methods

Self Check 18.11

Exactly what does the generic print method print when you pass an array of BankAccount objects containing two bank accounts with zero balances?

Self Check 18.12

Is the getFirst method of the Pair class a generic method?

Self Check 18.13

Consider this fill method:
public static <T> void fill(List<T> lst, T value)
{
    for (int i = 0; i < lst.size(); i++) { lst.set(i, value); }
}
If you have an array list ArrayList <String> a = new ArrayList<String>(10); how do you fill it with ten "*"?

Self Check 18.14

What happens if you pass 42 instead of "*" to the fill method?

Self Check 18.15

Consider this fill method:
public static <T> fill(T[] arr, T value)
{
   for (int i = 0; i < arr.length; i++) { arr[i] = value; }
}
What happens when you execute the following statements?
String[] a = new String[10];
fill(a, 42);

Constraining Type Variables

a "restricted area" sign

 

 

You can place restrictions on the type parameters of generic classes and methods.

Constraining Type Variables

Constraining Type Variables

Constraining Type Variables - Comparable Interface

Constraining Type Variables - Comparable Interface

Constraining Type Variables

Self Check 18.16

How would you constrain the type parameter for a generic BinarySearchTree class?

Self Check 18.17

Modify the min method to compute the minimum of an array list of elements that implements the Measurable interface.

Self Check 18.18

Could we have declared the min method of Self Check 17 without type parameters, like this?
public static Measurable min(ArrayList<Measurable> a)

Self Check 18.19

Could we have declared the min method of Self Check 17 without type parameters for arrays, like this?
public static Measurable min(Measurable[] a)

Self Check 18.20

How would you implement the generic average method for arrays?

Self Check 18.21

Is it necessary to use a generic average method for arrays of measurable objects?

Genericity and Inheritance

Wildcard Types

Name Syntax Meaning
Wildcard with lower bound ? extends B Any subtype of B
Wildcard with upper bound ? super B Any supertype of B
Unbounded wildcard ? Any type

Wildcard Types

Wildcard Types

Type Erasure

girl erasing chalk board

 

 

In the Java virtual machine, generic types are erased.

Type Erasure

Type Erasure

Type Erasure

Type Erasure

Type Erasure

Type Erasure

Self Check 18.22

Suppose we want to eliminate the type bound in the min method of Section 18.5, by declaring the parameter variable as an array of Comparable<E> objects. Why doesn't this work?

Self Check 18.23

What is the erasure of the print method in Section 18.3?

Self Check 18.24

Could the Stack example be implemented as follows?
public class Stack<E> 
{ 
   private E[] elements; 
   . . . 
   public Stack() 
   { 
      elements = (E[]) new Object[MAX_SIZE]; 
   } 
   . . . 
}

Self Check 18.25

The ArrayList<E> class has a method:
Object[] toArray()
Why doesn't the method return an E[]?

Self Check 18.26

The ArrayList<E> class has a second method:
E[] toArray(E[] a)
Why can this method return an array of type E[]? (Hint: Special Topic 18.2.)

Self Check 18.27

Why can't the method
static <T> T[] copyOf(T[] original, int newLength)
be implemented without reflection?