SlideShare a Scribd company logo
1 of 69
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 18 – Generic Classes
Copyright © 2014 by John Wiley & Sons. All rights reserved. 2
Chapter Goals
 To understand the objective of generic programming
 To implement generic classes and methods
 To explain the execution of generic methods in the virtual machine
 To describe the limitations of generic programming in Java
Copyright © 2014 by John Wiley & Sons. All rights reserved. 3
Generic Classes and Type Parameters
 Generic programming: creation of programming constructs that can
be used with many different types.
• In Java, achieved with type parameters or with inheritance
• Type parameter example: Java's ArrayList (e.g. ArrayList<String>)
• Inheritance example: LinkedList implemented in Section 15.2 can store
objects of any class
 Generic class: has one or more type parameters.
 A type parameter for ArrayList denotes the element type:
public class ArrayList<E>
{
public ArrayList() { . . . }
public void add(E element) { . . . }
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 4
Type Parameter
 Can be instantiated with class or interface type:
ArrayList<BankAccount>
ArrayList<Measurable>
 Cannot use a primitive type as a type parameter:
ArrayList<double> // Wrong!
 Use corresponding wrapper class instead:
ArrayList<Double>
Copyright © 2014 by John Wiley & Sons. All rights reserved. 5
Type Parameters
 Supplied type replaces type variable in class interface.
 Example: add in ArrayList<BankAccount> has type variable E
replaced with BankAccount:
public void add(BankAccount element)
 Contrast with LinkedList.add from Chapter 15:
public void add(Object element)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 6
Type Parameters Increase Safety
 Type parameters make generic code safer and easier to read:
• Impossible to add a String into an ArrayList<BankAccount>
• Can add a String into a non-generic LinkedList intended to hold bank
accounts
ArrayList<BankAccount> accounts1 = new ArrayList<BankAccount>();
LinkedList accounts2 = new LinkedList();
// Should hold BankAccount objects
accounts1.add("my savings"); // Compile-time error
accounts2.add("my savings"); // Not detected at compile time
. . .
BankAccount account = (BankAccount) accounts2.getFirst();
// Run-time error
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
Self Check 18.1
Answer: HashMap<String, Integer>
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 8
Self Check 18.2
Answer: It uses inheritance.
The binary search tree class in Chapter 16 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 variables?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 9
Self Check 18.3
Answer: This is a compile-time error. You cannot assign the
Integer expression a.get(0) to a String.
Does the following code contain an error? If so, is it a compile-
time or run-time error?
ArrayList<Integer> a = new ArrayList<Integer>();
String s = a.get(0);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 10
Self Check 18.4
Answer: This is a compile-time error. The compiler won't
convert 3 to a Double. Remedy: Call a.add(3.0).
Does the following code contain an error? If so, is it a compile-
time or run-time error?
ArrayList<Double> a = new ArrayList<Double>();
a.add(3);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 11
Self Check 18.5
Answer: This is a run-time error. a.removeFirst() yields a
String that cannot be converted into a Double. Remedy:
Call a.addFirst(3.14);
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();
Copyright © 2014 by John Wiley & Sons. All rights reserved. 12
Implementing Generic Classes
 Example: simple generic class that stores pairs of arbitrary
objects such as:
Pair<String, Integer> result =
new Pair<String, Integer>("Harry Hacker", 1729);
 Methods getFirst and getSecond retrieve first and second
values of pair:
String name = result.getFirst();
Integer number = result.getSecond();
 Example of use: return two values at the same time (method
returns a Pair).
 Generic Pair class requires two type parameters, one for each
element type enclosed in angle brackets:
public class Pair<T, S>
Copyright © 2014 by John Wiley & Sons. All rights reserved. 13
Implementing Generic Types
 Use short uppercase names for type variables.
 Examples
Copyright © 2014 by John Wiley & Sons. All rights reserved. 14
Implementing Generic Types
 Place the type variables for a generic class after the class
name, enclosed in angle brackets (< and >):
public class Pair<T, S>
 When you declare the instance variables and methods of the
Pair class, use the variable T for the first element type and S for
the second element type.
 Use type parameters for the types of generic instance
variables, method parameter variables, and return values.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
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; }
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 16
Syntax 18.1 Declaring a Generic Class
Copyright © 2014 by John Wiley & Sons. All rights reserved. 17
section_2/Pair.java
1 /**
2 This class collects a pair of elements of different types.
3 */
4 public class Pair<T, S>
5 {
6 private T first;
7 private S second;
8
9 /**
10 Constructs a pair containing two given elements.
11 @param firstElement the first element
12 @param secondElement the second element
13 */
14 public Pair(T firstElement, S secondElement)
15 {
16 first = firstElement;
17 second = secondElement;
18 }
19
20 /**
21 Gets the first element of this pair.
22 @return the first element
23 */
24 public T getFirst() { return first; }
25
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
section_2/Pair.java
26 /**
27 Gets the second element of this pair.
28 @return the second element
29 */
30 public S getSecond() { return second; }
31
32 public String toString() { return "(" + first + ", " + second + ")"; }
33 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
section_2/PairDemo.java
1 public class PairDemo
2 {
3 public static void main(String[] args)
4 {
5 String[] names = { "Tom", "Diana", "Harry" };
6 Pair<String, Integer> result = firstContaining(names, "a");
7 System.out.println(result.getFirst());
8 System.out.println("Expected: Diana");
9 System.out.println(result.getSecond());
10 System.out.println("Expected: 1");
11 }
12
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
section_2/PairDemo.java
13 /**
14 Gets the first String containing a given string, together
15 with its index.
16 @param strings an array of strings
17 @param sub a string
18 @return a pair (strings[i], i) where strings[i] is the first
19 strings[i] containing str, or a pair (null, -1) if there is no
20 match.
21 */
22 public static Pair<String, Integer> firstContaining(
23 String[] strings, String sub)
24 {
25 for (int i = 0; i < strings.length; i++)
26 {
27 if (strings[i].contains(sub))
28 {
29 return new Pair<String, Integer>(strings[i], i);
30 }
31 }
32 return new Pair<String, Integer>(null, -1);
33 }
34 }
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
section_2/PairDemo.java
Program Run:
Diana
Expected: Diana
1
Expected: 1
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
Self Check 18.6
Answer:
new Pair<String, String>("Hello", "World")
How would you use the generic Pair class to construct a pair of
strings "Hello" and "World"?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
Self Check 18.7
Answer:
new Pair<String, Integer>(“Hello”, 1729)
How would you use the generic Pair class to construct a pair
containing "Hello" and 1729?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 24
Self Check 18.8
Answer: An ArrayList<Pair<String, Integer>> contains
multiple pairs, for example [(Tom, 1), (Harry, 3)]. A
Pair<ArrayList<String>, Integer> contains a list of strings
and a single integer, such as ([Tom, Harry], 1).
What is the difference between an ArrayList<Pair<String,
Integer>> and a Pair<ArrayList<String>, Integer>?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 25
Self Check 18.9
Answer:
public static Pair<Double, Double> roots(Double x)
{
if (x >= 0)
{
double r = Math.sqrt(x);
return new Pair<Double, Double>(r, -r);
}
else { return null; }
}
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 26
Self Check 18.10
Answer: You have three type parameters: Triple<T, S, U>.
Add an instance variable U third, a constructor argument
for initializing it, and a method U getThird() for returning it.
How would you implement a class Triple that collects three
values of arbitrary types?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 27
Generic Methods
 Generic method: method with a type parameter.
 Can be declared inside non-generic class .
 Example: Declare a method that can print an array of any type:
public class ArrayUtil
{
/**
Prints all elements in an array.
@param a the array to print
*/
public <T> static void print(T[] a)
{
. . .
}
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 28
Generic Methods
 Often easier to see how to implement a generic method by
starting with a concrete example.
 Example: print the elements in an array of strings:
public class ArrayUtil
{
public static void print(String[] a)
{
for (String e : a)
{
System.out.print(e + " ");
}
System.out.println();
}
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 29
Generic Methods
 In order to make the method into a generic method:
• Replace String with a type parameter, say E, to denote the element type
• Add the type parameters between the method's modifiers and return type
public static <E> void print(E[] a)
{
for ( E e : a)
System.out.print(e + " ");
System.out.println();
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 30
Generic Methods
 When calling a generic method, you need not instantiate the
type variables:
Rectangle[] rectangles = . . .;
ArrayUtil.print(rectangles);
 The compiler deduces that E is Rectangle.
 You can also define generic methods that are not static.
 You can even have generic methods in generic classes.
 Cannot replace type variables with primitive types.
• Example: cannot use the generic print method to print an array of type
int[]
Copyright © 2014 by John Wiley & Sons. All rights reserved. 31
Syntax 18.1 Declaring a Generic Method
Copyright © 2014 by John Wiley & Sons. All rights reserved. 32
Self Check 18.11
Answer: The output depends on the definition of the toString
method in the BankAccount class.
Exactly what does the generic print method print when you
pass an array of BankAccount objects containing two bank
accounts with zero balances?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 33
Self Check 18.12
Answer: No – the method has no type parameters. It is an
ordinary method in a generic class.
Is the getFirst method of the Pair class a generic method?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 34
Self Check 18.13
Answer: fill(a, "*");
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 "*"?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 35
Self Check 18.14
Answer: You get a compile-time error. An integer cannot
be converted to a string.
What happens if you pass 42 instead of "*" to the fill method?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 36
Self Check 18.15
Answer: You get a run-time error. Unfortunately, the call
compiles, with T = Object. This choice is justified because
a String[] array is convertible to an Object[] array, and 42
becomes new Integer(42), which is convertible to an
Object. But when the program tries to store an Integer in
the String[] array, an exception is thrown.
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);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 37
Constraining Type Variables
You can place restrictions on
the type parameters of generic
classes and methods.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 38
Constraining Type Variables
 Type variables can be constrained with bounds.
 A generic method, average, needs to be able to measure the
objects.
 Measurable interface from Section 10.1:
public interface Measurable
{
double getMeasure();
}
 We can constrain the type of the elements to those that
implement the Measurable type:
public static <E extends Measurable>
double average(ArrayList<E> objects)
 This means, “E or one of its superclasses extends or
implements Measurable”.
• We say that E is a subtype of the Measurable type.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 39
Constraining Type Variables
 Completed average method:
public static <E extends Measurable>
double average(ArrayList<E> objects)
{
if (objects.size() == 0) { return 0; }
double sum = 0;
for (E obj : objects)
{
sum = sum + obj.getMeasure();
}
return sum / objects.size();
}
 In the call obj.getMeasure()
• It is legal to apply the getMeasure method to obj
• obj has type E, and E is a subtype of Measurable.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
Constraining Type Variables - Comparable Interface
 Comparable interface is a generic type.
 The type parameter specifies the type of the parameter variable
of the compareTo method:
public interface Comparable<T>
{
int compareTo(T other);
}
 String class implements Comparable<String>
• Strings can be compared to other Strings
• But not with objects of a different class
Copyright © 2014 by John Wiley & Sons. All rights reserved. 41
Constraining Type Variables - Comparable Interface
 When writing a generic method min to find the smallest element
in an array list,
• Require that type parameter E implements Comparable<E>
public static <E extends Comparable<E>>
E min(ArrayList<E> objects)
{
E smallest = objects.get(0);
for (int i = 1; i <objects.size(); i++)
{
E obj = objects.get(i);
if (obj.compareTo(smallest) < 0)
{
smallest = obj;
}
}
return smallest;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 42
Constraining Type Variables - Comparable Interface
 Because of the type constraint, obj must have a method of this
form:
int compareTo(E other)
• So the the following call is valid
obj.compareTo(smallest)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
Constraining Type Variables
 Very occasionally, you need to supply two or more type bounds:
<E extends Comparable<E> & Cloneable>
 extends, when applied to type parameters, actually means
“extends or implements”
 The bounds can be either classes or interfaces
 Type parameters can be replaced with a class or interface type
Copyright © 2014 by John Wiley & Sons. All rights reserved. 44
Self Check 18.16
Answer:
public class BinarySearchTree
<E extends Comparable<E>>
or, if you read Special Topic 18.1,
public class BinarySearchTree
<E extends Comparable<? super E>>
How would you constrain the type parameter for a generic
BinarySearchTree class?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 45
Self Check 18.17
Answer:
public static <E extends Measurable>
E min(ArrayList<E> objects)
{
E smallest = objects.get(0);
for (int i = 1; i < objects.size(); i++)
{
E obj = objects.get(i);
if (obj.getMeasure() < smallest.getMeasure())
{
smallest = obj;
}
}
return smallest;
}
Modify the min method to compute the minimum of an array list
of elements that implements the Measurable interface.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 46
Self Check 18.18
Answer: No. As described in Common Error 18.1, you cannot
convert an ArrayList<BankAccount> to an
ArrayList<Measurable>, even if BankAccount implements
Measurable.
Could we have declared the min method of Self Check 17
without type parameters, like this?
public static Measurable min(ArrayList<Measurable> a)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 47
Self Check 18.19
Answer: Yes, but this method would not be as useful.
Suppose accounts is an array of BankAccount objects.
With this method, min(accounts) would return a result of
type Measurable, whereas the generic method yields a
BankAccount.
Could we have declared the min method of Self Check 17
without type parameters for arrays, like this?
public static Measurable min(Measurable[] a)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 48
Self Check 18.20
Answer:
public static <E extends Measurable>
double average(E[] objects)
{
if (objects.length == 0) { return 0; }
double sum = 0;
for (E obj : objects)
{
sum = sum + obj.getMeasure();
}
return sum / objects.length;
}
How would you implement the generic average method for
arrays?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 49
Self Check 18.21
Is it necessary to use a generic average method for arrays of
Measurable objects?
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 50
Self Check 18.21
Answer: No. You can define
public static double average(Measurable[] objects)
{
if (objects.length == 0) { return 0; }
double sum = 0;
for (Measurable obj : objects)
{
sum = sum + obj.getMeasure();
}
return sum / objects.length;
}
For example, if BankAccount implements Measurable, a
BankAccount[] array is convertible to a Measurable[] array.
Contrast with Self Check 19, where the return type was a
generic type. Here, the return type is double, and there is
no need for using generic types.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 51
Genericity and Inheritance
 One can not assign a subclass list to a superclass list.
 ArrayList<SavingsAccount> is not a subclass of
ArrayList<BankAccount>.
• Even though SavingsAccount is a subclass of BankAccount
ArrayList<SavingsAccount> savingsAccounts =
new ArrayList<SavingsAccount>();
ArrayList<BankAccount> bankAccounts = savingsAccounts;
// Not legal - compile-time error
 However, you can do the equivalent thing with arrays:
SavingsAccount[] savingsAccounts =
new SavingsAccount[10];
BankAccount bankAccounts = savingsAccounts; // Legal
 But this assignment will give a run-time error:
BankAccount harrysChecking = new CheckingAccount();
bankAccounts[0] = harrysChecking;
// Throws ArrayStoreException
Copyright © 2014 by John Wiley & Sons. All rights reserved. 52
Wildcard Types
Copyright © 2014 by John Wiley & Sons. All rights reserved. 53
Wildcard Types
 Wildcard types are used to formulate subtle constraints on type
parameters.
 A wildcard type is a type that can remain unknown.
 A method in a LinkedList class to add all elements of LinkedList
other:
• other can be of any subclass of E
public void addAll(LinkedList<? extends E> other)
{
ListIterator<E> iter = other.listIterator();
while (iter.hasNext()) add(iter.next());
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
Wildcard Types
 This declaration is too restrictive for the min method:
public static <E extends Comparable<E>> E min(E[] a)
 Type parameter of the Comparable interface should be any
supertype of the array list’s element type:
public static <E extends Comparable<? super E>> E min(E[] a)
 A method in the Collections class which uses an unbounded
wildcard:
static void reverse(List<?> list)
 You can think of that declaration as a shorthand for:
static void <T> reverse(List<T> list)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
Type Erasure
In the Java virtual machine,
generic types are erased.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
Type Erasure
 The virtual machine erases type parameters, replacing them
with their bounds or Objects. For example, generic class
Pair<T, S> turns into the following raw class:
public class Pair
{
private Object first;
private Object second;
public Pair(Object firstElement,
Object secondElement)
{
first = firstElement;
second = secondElement;
}
public Object getFirst() { return first; }
public Object getSecond() { return second; }
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 57
Type Erasure
 Same process is applied to generic methods.
 In this generic method:
public static <E extends Measurable> E min(E[] objects)
{
E smallest = objects[0];
for (int i = 1; i < objects.length; i++)
{
E obj = objects[i];
if (obj.getMeasure() < smallest.getMeasure())
{
smallest = obj;
}
}
return smallest;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 58
Type Erasure
 The type parameter Is replaced with its bound Measurable:
public static Measurable min(Measurable[] objects)
{
Measurable smallest = objects[0];
for (int i = 1; i < objects.length; i++)
{
Measurable obj = objects[i];
if (obj.getMeasure() < smallest.getMeasure())
{
smallest = obj;
}
}
return smallest;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 59
Type Erasure
 Knowing about type erasure helps you understand limitations of
Java generics.
 You cannot construct new objects of a generic type.
 For example, trying to fill an array with copies of default objects
would be wrong:
public static <E> void fillWithDefaults(E[] a)
{
for (int i = 0; i < a.length; i++)
a[i] = new E(); // ERROR
}
 Type erasure yields:
public static void fillWithDefaults(Object[] a)
{
for (int i = 0; i < a.length; i++)
a[i] = new Object(); // Not useful
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 60
Type Erasure
 To solve this particular problem, you can supply a default
object:
public static <E> void fillWithDefaults(E[] a, E defaultValue)
{
for (int i = 0; i < a.length; i++)
a[i] = defaultValue;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 61
Type Erasure
 You cannot construct an array of a generic type:
public class Stack<E>
{
private E[] elements;
. . .
public Stack()
{
elements = new E[MAX_SIZE]; // Error
}
}
 Because the array construction expression new E[] would be
erased to new Object[].
Copyright © 2014 by John Wiley & Sons. All rights reserved. 62
Type Erasure
 One remedy is to use an array list instead:
public class Stack<E>
{
private ArrayList<E> elements;
. . .
public Stack()
{
elements = new ArrayList<E>(); // Ok
}
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 63
Type Erasure
 Another solution is to use an array of objects and cast when
reading elements from the array:
public class Stack<E>
{
private Object[] elements;
private int currentSize;
. . .
public Stack()
{
elements = new Object[MAX_SIZE]; // Ok
}
. . .
public E pop()
{
size--;
return (E) elements[currentSize];
}
}
 The cast (E) generates a warning because it cannot be
checked at compile time
Copyright © 2014 by John Wiley & Sons. All rights reserved. 64
Self Check 18.22
Answer:
public static <E>
Comparable<E> min(Comparable<E>[] objects)
is an error. You cannot have an array of a generic type.
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?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 65
Self Check 18.23
Answer:
public static void print(Object[] a)
{
for (Object e : a)
{
System.out.print(e + " ");
}
System.out.println();
}
What is the erasure of the print method in Section 18.3?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 66
Self Check 18.24
Answer: This code compiles (with a warning), but it is a poor
technique. In the future, if type erasure no longer happens,
the code will be wrong. The cast from Object[] to String[]
will cause a class cast exception.
Could the Stack example be implemented as follows?
public class Stack<E>
{
private E[] elements;
. . .
public Stack()
{
elements = (E[]) new Object[MAX_SIZE];
}
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 67
Self Check 18.25
Answer: Internally, ArrayList uses an Object[] array. Because
of type erasure, it can’t make an E[] array. The best it can
do is make a copy of its internal Object[] array.
The ArrayList<E> class has a method:
Object[] toArray()
Why doesn't the method return an E[]?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 68
Self Check 18.26
Answer: It can use reflection to discover the element type of
the parameter a, and then construct another array with that
element type (or just call the Arrays.copyOf method).
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.)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 69
Self Check 18.27
Answer: The method needs to construct a new array of type
T. However, that is not possible in Java without reflection.
Why can't the method
static <T> T[] copyOf(T[] original, int newLength)
be implemented without reflection?

More Related Content

What's hot

What's hot (20)

Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
 
Icom4015 lecture12-s16
Icom4015 lecture12-s16Icom4015 lecture12-s16
Icom4015 lecture12-s16
 
Icom4015 lecture3-f17
Icom4015 lecture3-f17Icom4015 lecture3-f17
Icom4015 lecture3-f17
 
Icom4015 lecture3-s18
Icom4015 lecture3-s18Icom4015 lecture3-s18
Icom4015 lecture3-s18
 
Icom4015 lecture3-f17
Icom4015 lecture3-f17Icom4015 lecture3-f17
Icom4015 lecture3-f17
 
Icom4015 lecture9-f16
Icom4015 lecture9-f16Icom4015 lecture9-f16
Icom4015 lecture9-f16
 
CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17
 
Icom4015 lecture8-f16
Icom4015 lecture8-f16Icom4015 lecture8-f16
Icom4015 lecture8-f16
 
Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016
 
Icom4015 lecture11-s16
Icom4015 lecture11-s16Icom4015 lecture11-s16
Icom4015 lecture11-s16
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Java™ (OOP) - Chapter 6: "Arrays"
Java™ (OOP) - Chapter 6: "Arrays"Java™ (OOP) - Chapter 6: "Arrays"
Java™ (OOP) - Chapter 6: "Arrays"
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Java small steps - 2019
Java   small steps - 2019Java   small steps - 2019
Java small steps - 2019
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 

Similar to Icom4015 lecture15-f16

Similar to Icom4015 lecture15-f16 (20)

Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java execise
Java execiseJava execise
Java execise
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Java Generics
Java GenericsJava Generics
Java Generics
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Adapt your code from Assignment 2 to use both a Java API ArrayList a.pdf
Adapt your code from Assignment 2 to use both a Java API ArrayList a.pdfAdapt your code from Assignment 2 to use both a Java API ArrayList a.pdf
Adapt your code from Assignment 2 to use both a Java API ArrayList a.pdf
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
 
06slide
06slide06slide
06slide
 
Collections
CollectionsCollections
Collections
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
Java generics
Java genericsJava generics
Java generics
 

Recently uploaded

Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Christo Ananth
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 

Recently uploaded (20)

Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 

Icom4015 lecture15-f16

  • 1. Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Chapter 18 – Generic Classes
  • 2. Copyright © 2014 by John Wiley & Sons. All rights reserved. 2 Chapter Goals  To understand the objective of generic programming  To implement generic classes and methods  To explain the execution of generic methods in the virtual machine  To describe the limitations of generic programming in Java
  • 3. Copyright © 2014 by John Wiley & Sons. All rights reserved. 3 Generic Classes and Type Parameters  Generic programming: creation of programming constructs that can be used with many different types. • In Java, achieved with type parameters or with inheritance • Type parameter example: Java's ArrayList (e.g. ArrayList<String>) • Inheritance example: LinkedList implemented in Section 15.2 can store objects of any class  Generic class: has one or more type parameters.  A type parameter for ArrayList denotes the element type: public class ArrayList<E> { public ArrayList() { . . . } public void add(E element) { . . . } . . . }
  • 4. Copyright © 2014 by John Wiley & Sons. All rights reserved. 4 Type Parameter  Can be instantiated with class or interface type: ArrayList<BankAccount> ArrayList<Measurable>  Cannot use a primitive type as a type parameter: ArrayList<double> // Wrong!  Use corresponding wrapper class instead: ArrayList<Double>
  • 5. Copyright © 2014 by John Wiley & Sons. All rights reserved. 5 Type Parameters  Supplied type replaces type variable in class interface.  Example: add in ArrayList<BankAccount> has type variable E replaced with BankAccount: public void add(BankAccount element)  Contrast with LinkedList.add from Chapter 15: public void add(Object element)
  • 6. Copyright © 2014 by John Wiley & Sons. All rights reserved. 6 Type Parameters Increase Safety  Type parameters make generic code safer and easier to read: • Impossible to add a String into an ArrayList<BankAccount> • Can add a String into a non-generic LinkedList intended to hold bank accounts ArrayList<BankAccount> accounts1 = new ArrayList<BankAccount>(); LinkedList accounts2 = new LinkedList(); // Should hold BankAccount objects accounts1.add("my savings"); // Compile-time error accounts2.add("my savings"); // Not detected at compile time . . . BankAccount account = (BankAccount) accounts2.getFirst(); // Run-time error
  • 7. Copyright © 2014 by John Wiley & Sons. All rights reserved. 7 Self Check 18.1 Answer: HashMap<String, Integer> 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.
  • 8. Copyright © 2014 by John Wiley & Sons. All rights reserved. 8 Self Check 18.2 Answer: It uses inheritance. The binary search tree class in Chapter 16 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 variables?
  • 9. Copyright © 2014 by John Wiley & Sons. All rights reserved. 9 Self Check 18.3 Answer: This is a compile-time error. You cannot assign the Integer expression a.get(0) to a String. Does the following code contain an error? If so, is it a compile- time or run-time error? ArrayList<Integer> a = new ArrayList<Integer>(); String s = a.get(0);
  • 10. Copyright © 2014 by John Wiley & Sons. All rights reserved. 10 Self Check 18.4 Answer: This is a compile-time error. The compiler won't convert 3 to a Double. Remedy: Call a.add(3.0). Does the following code contain an error? If so, is it a compile- time or run-time error? ArrayList<Double> a = new ArrayList<Double>(); a.add(3);
  • 11. Copyright © 2014 by John Wiley & Sons. All rights reserved. 11 Self Check 18.5 Answer: This is a run-time error. a.removeFirst() yields a String that cannot be converted into a Double. Remedy: Call a.addFirst(3.14); 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();
  • 12. Copyright © 2014 by John Wiley & Sons. All rights reserved. 12 Implementing Generic Classes  Example: simple generic class that stores pairs of arbitrary objects such as: Pair<String, Integer> result = new Pair<String, Integer>("Harry Hacker", 1729);  Methods getFirst and getSecond retrieve first and second values of pair: String name = result.getFirst(); Integer number = result.getSecond();  Example of use: return two values at the same time (method returns a Pair).  Generic Pair class requires two type parameters, one for each element type enclosed in angle brackets: public class Pair<T, S>
  • 13. Copyright © 2014 by John Wiley & Sons. All rights reserved. 13 Implementing Generic Types  Use short uppercase names for type variables.  Examples
  • 14. Copyright © 2014 by John Wiley & Sons. All rights reserved. 14 Implementing Generic Types  Place the type variables for a generic class after the class name, enclosed in angle brackets (< and >): public class Pair<T, S>  When you declare the instance variables and methods of the Pair class, use the variable T for the first element type and S for the second element type.  Use type parameters for the types of generic instance variables, method parameter variables, and return values.
  • 15. Copyright © 2014 by John Wiley & Sons. All rights reserved. 15 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; } }
  • 16. Copyright © 2014 by John Wiley & Sons. All rights reserved. 16 Syntax 18.1 Declaring a Generic Class
  • 17. Copyright © 2014 by John Wiley & Sons. All rights reserved. 17 section_2/Pair.java 1 /** 2 This class collects a pair of elements of different types. 3 */ 4 public class Pair<T, S> 5 { 6 private T first; 7 private S second; 8 9 /** 10 Constructs a pair containing two given elements. 11 @param firstElement the first element 12 @param secondElement the second element 13 */ 14 public Pair(T firstElement, S secondElement) 15 { 16 first = firstElement; 17 second = secondElement; 18 } 19 20 /** 21 Gets the first element of this pair. 22 @return the first element 23 */ 24 public T getFirst() { return first; } 25 Continued
  • 18. Copyright © 2014 by John Wiley & Sons. All rights reserved. 18 section_2/Pair.java 26 /** 27 Gets the second element of this pair. 28 @return the second element 29 */ 30 public S getSecond() { return second; } 31 32 public String toString() { return "(" + first + ", " + second + ")"; } 33 }
  • 19. Copyright © 2014 by John Wiley & Sons. All rights reserved. 19 section_2/PairDemo.java 1 public class PairDemo 2 { 3 public static void main(String[] args) 4 { 5 String[] names = { "Tom", "Diana", "Harry" }; 6 Pair<String, Integer> result = firstContaining(names, "a"); 7 System.out.println(result.getFirst()); 8 System.out.println("Expected: Diana"); 9 System.out.println(result.getSecond()); 10 System.out.println("Expected: 1"); 11 } 12 Continued
  • 20. Copyright © 2014 by John Wiley & Sons. All rights reserved. 20 section_2/PairDemo.java 13 /** 14 Gets the first String containing a given string, together 15 with its index. 16 @param strings an array of strings 17 @param sub a string 18 @return a pair (strings[i], i) where strings[i] is the first 19 strings[i] containing str, or a pair (null, -1) if there is no 20 match. 21 */ 22 public static Pair<String, Integer> firstContaining( 23 String[] strings, String sub) 24 { 25 for (int i = 0; i < strings.length; i++) 26 { 27 if (strings[i].contains(sub)) 28 { 29 return new Pair<String, Integer>(strings[i], i); 30 } 31 } 32 return new Pair<String, Integer>(null, -1); 33 } 34 } Continued
  • 21. Copyright © 2014 by John Wiley & Sons. All rights reserved. 21 section_2/PairDemo.java Program Run: Diana Expected: Diana 1 Expected: 1
  • 22. Copyright © 2014 by John Wiley & Sons. All rights reserved. 22 Self Check 18.6 Answer: new Pair<String, String>("Hello", "World") How would you use the generic Pair class to construct a pair of strings "Hello" and "World"?
  • 23. Copyright © 2014 by John Wiley & Sons. All rights reserved. 23 Self Check 18.7 Answer: new Pair<String, Integer>(“Hello”, 1729) How would you use the generic Pair class to construct a pair containing "Hello" and 1729?
  • 24. Copyright © 2014 by John Wiley & Sons. All rights reserved. 24 Self Check 18.8 Answer: An ArrayList<Pair<String, Integer>> contains multiple pairs, for example [(Tom, 1), (Harry, 3)]. A Pair<ArrayList<String>, Integer> contains a list of strings and a single integer, such as ([Tom, Harry], 1). What is the difference between an ArrayList<Pair<String, Integer>> and a Pair<ArrayList<String>, Integer>?
  • 25. Copyright © 2014 by John Wiley & Sons. All rights reserved. 25 Self Check 18.9 Answer: public static Pair<Double, Double> roots(Double x) { if (x >= 0) { double r = Math.sqrt(x); return new Pair<Double, Double>(r, -r); } else { return null; } } 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.
  • 26. Copyright © 2014 by John Wiley & Sons. All rights reserved. 26 Self Check 18.10 Answer: You have three type parameters: Triple<T, S, U>. Add an instance variable U third, a constructor argument for initializing it, and a method U getThird() for returning it. How would you implement a class Triple that collects three values of arbitrary types?
  • 27. Copyright © 2014 by John Wiley & Sons. All rights reserved. 27 Generic Methods  Generic method: method with a type parameter.  Can be declared inside non-generic class .  Example: Declare a method that can print an array of any type: public class ArrayUtil { /** Prints all elements in an array. @param a the array to print */ public <T> static void print(T[] a) { . . . } . . . }
  • 28. Copyright © 2014 by John Wiley & Sons. All rights reserved. 28 Generic Methods  Often easier to see how to implement a generic method by starting with a concrete example.  Example: print the elements in an array of strings: public class ArrayUtil { public static void print(String[] a) { for (String e : a) { System.out.print(e + " "); } System.out.println(); } . . . }
  • 29. Copyright © 2014 by John Wiley & Sons. All rights reserved. 29 Generic Methods  In order to make the method into a generic method: • Replace String with a type parameter, say E, to denote the element type • Add the type parameters between the method's modifiers and return type public static <E> void print(E[] a) { for ( E e : a) System.out.print(e + " "); System.out.println(); }
  • 30. Copyright © 2014 by John Wiley & Sons. All rights reserved. 30 Generic Methods  When calling a generic method, you need not instantiate the type variables: Rectangle[] rectangles = . . .; ArrayUtil.print(rectangles);  The compiler deduces that E is Rectangle.  You can also define generic methods that are not static.  You can even have generic methods in generic classes.  Cannot replace type variables with primitive types. • Example: cannot use the generic print method to print an array of type int[]
  • 31. Copyright © 2014 by John Wiley & Sons. All rights reserved. 31 Syntax 18.1 Declaring a Generic Method
  • 32. Copyright © 2014 by John Wiley & Sons. All rights reserved. 32 Self Check 18.11 Answer: The output depends on the definition of the toString method in the BankAccount class. Exactly what does the generic print method print when you pass an array of BankAccount objects containing two bank accounts with zero balances?
  • 33. Copyright © 2014 by John Wiley & Sons. All rights reserved. 33 Self Check 18.12 Answer: No – the method has no type parameters. It is an ordinary method in a generic class. Is the getFirst method of the Pair class a generic method?
  • 34. Copyright © 2014 by John Wiley & Sons. All rights reserved. 34 Self Check 18.13 Answer: fill(a, "*"); 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 "*"?
  • 35. Copyright © 2014 by John Wiley & Sons. All rights reserved. 35 Self Check 18.14 Answer: You get a compile-time error. An integer cannot be converted to a string. What happens if you pass 42 instead of "*" to the fill method?
  • 36. Copyright © 2014 by John Wiley & Sons. All rights reserved. 36 Self Check 18.15 Answer: You get a run-time error. Unfortunately, the call compiles, with T = Object. This choice is justified because a String[] array is convertible to an Object[] array, and 42 becomes new Integer(42), which is convertible to an Object. But when the program tries to store an Integer in the String[] array, an exception is thrown. 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);
  • 37. Copyright © 2014 by John Wiley & Sons. All rights reserved. 37 Constraining Type Variables You can place restrictions on the type parameters of generic classes and methods.
  • 38. Copyright © 2014 by John Wiley & Sons. All rights reserved. 38 Constraining Type Variables  Type variables can be constrained with bounds.  A generic method, average, needs to be able to measure the objects.  Measurable interface from Section 10.1: public interface Measurable { double getMeasure(); }  We can constrain the type of the elements to those that implement the Measurable type: public static <E extends Measurable> double average(ArrayList<E> objects)  This means, “E or one of its superclasses extends or implements Measurable”. • We say that E is a subtype of the Measurable type.
  • 39. Copyright © 2014 by John Wiley & Sons. All rights reserved. 39 Constraining Type Variables  Completed average method: public static <E extends Measurable> double average(ArrayList<E> objects) { if (objects.size() == 0) { return 0; } double sum = 0; for (E obj : objects) { sum = sum + obj.getMeasure(); } return sum / objects.size(); }  In the call obj.getMeasure() • It is legal to apply the getMeasure method to obj • obj has type E, and E is a subtype of Measurable.
  • 40. Copyright © 2014 by John Wiley & Sons. All rights reserved. 40 Constraining Type Variables - Comparable Interface  Comparable interface is a generic type.  The type parameter specifies the type of the parameter variable of the compareTo method: public interface Comparable<T> { int compareTo(T other); }  String class implements Comparable<String> • Strings can be compared to other Strings • But not with objects of a different class
  • 41. Copyright © 2014 by John Wiley & Sons. All rights reserved. 41 Constraining Type Variables - Comparable Interface  When writing a generic method min to find the smallest element in an array list, • Require that type parameter E implements Comparable<E> public static <E extends Comparable<E>> E min(ArrayList<E> objects) { E smallest = objects.get(0); for (int i = 1; i <objects.size(); i++) { E obj = objects.get(i); if (obj.compareTo(smallest) < 0) { smallest = obj; } } return smallest; }
  • 42. Copyright © 2014 by John Wiley & Sons. All rights reserved. 42 Constraining Type Variables - Comparable Interface  Because of the type constraint, obj must have a method of this form: int compareTo(E other) • So the the following call is valid obj.compareTo(smallest)
  • 43. Copyright © 2014 by John Wiley & Sons. All rights reserved. 43 Constraining Type Variables  Very occasionally, you need to supply two or more type bounds: <E extends Comparable<E> & Cloneable>  extends, when applied to type parameters, actually means “extends or implements”  The bounds can be either classes or interfaces  Type parameters can be replaced with a class or interface type
  • 44. Copyright © 2014 by John Wiley & Sons. All rights reserved. 44 Self Check 18.16 Answer: public class BinarySearchTree <E extends Comparable<E>> or, if you read Special Topic 18.1, public class BinarySearchTree <E extends Comparable<? super E>> How would you constrain the type parameter for a generic BinarySearchTree class?
  • 45. Copyright © 2014 by John Wiley & Sons. All rights reserved. 45 Self Check 18.17 Answer: public static <E extends Measurable> E min(ArrayList<E> objects) { E smallest = objects.get(0); for (int i = 1; i < objects.size(); i++) { E obj = objects.get(i); if (obj.getMeasure() < smallest.getMeasure()) { smallest = obj; } } return smallest; } Modify the min method to compute the minimum of an array list of elements that implements the Measurable interface.
  • 46. Copyright © 2014 by John Wiley & Sons. All rights reserved. 46 Self Check 18.18 Answer: No. As described in Common Error 18.1, you cannot convert an ArrayList<BankAccount> to an ArrayList<Measurable>, even if BankAccount implements Measurable. Could we have declared the min method of Self Check 17 without type parameters, like this? public static Measurable min(ArrayList<Measurable> a)
  • 47. Copyright © 2014 by John Wiley & Sons. All rights reserved. 47 Self Check 18.19 Answer: Yes, but this method would not be as useful. Suppose accounts is an array of BankAccount objects. With this method, min(accounts) would return a result of type Measurable, whereas the generic method yields a BankAccount. Could we have declared the min method of Self Check 17 without type parameters for arrays, like this? public static Measurable min(Measurable[] a)
  • 48. Copyright © 2014 by John Wiley & Sons. All rights reserved. 48 Self Check 18.20 Answer: public static <E extends Measurable> double average(E[] objects) { if (objects.length == 0) { return 0; } double sum = 0; for (E obj : objects) { sum = sum + obj.getMeasure(); } return sum / objects.length; } How would you implement the generic average method for arrays?
  • 49. Copyright © 2014 by John Wiley & Sons. All rights reserved. 49 Self Check 18.21 Is it necessary to use a generic average method for arrays of Measurable objects? Continued
  • 50. Copyright © 2014 by John Wiley & Sons. All rights reserved. 50 Self Check 18.21 Answer: No. You can define public static double average(Measurable[] objects) { if (objects.length == 0) { return 0; } double sum = 0; for (Measurable obj : objects) { sum = sum + obj.getMeasure(); } return sum / objects.length; } For example, if BankAccount implements Measurable, a BankAccount[] array is convertible to a Measurable[] array. Contrast with Self Check 19, where the return type was a generic type. Here, the return type is double, and there is no need for using generic types.
  • 51. Copyright © 2014 by John Wiley & Sons. All rights reserved. 51 Genericity and Inheritance  One can not assign a subclass list to a superclass list.  ArrayList<SavingsAccount> is not a subclass of ArrayList<BankAccount>. • Even though SavingsAccount is a subclass of BankAccount ArrayList<SavingsAccount> savingsAccounts = new ArrayList<SavingsAccount>(); ArrayList<BankAccount> bankAccounts = savingsAccounts; // Not legal - compile-time error  However, you can do the equivalent thing with arrays: SavingsAccount[] savingsAccounts = new SavingsAccount[10]; BankAccount bankAccounts = savingsAccounts; // Legal  But this assignment will give a run-time error: BankAccount harrysChecking = new CheckingAccount(); bankAccounts[0] = harrysChecking; // Throws ArrayStoreException
  • 52. Copyright © 2014 by John Wiley & Sons. All rights reserved. 52 Wildcard Types
  • 53. Copyright © 2014 by John Wiley & Sons. All rights reserved. 53 Wildcard Types  Wildcard types are used to formulate subtle constraints on type parameters.  A wildcard type is a type that can remain unknown.  A method in a LinkedList class to add all elements of LinkedList other: • other can be of any subclass of E public void addAll(LinkedList<? extends E> other) { ListIterator<E> iter = other.listIterator(); while (iter.hasNext()) add(iter.next()); }
  • 54. Copyright © 2014 by John Wiley & Sons. All rights reserved. 54 Wildcard Types  This declaration is too restrictive for the min method: public static <E extends Comparable<E>> E min(E[] a)  Type parameter of the Comparable interface should be any supertype of the array list’s element type: public static <E extends Comparable<? super E>> E min(E[] a)  A method in the Collections class which uses an unbounded wildcard: static void reverse(List<?> list)  You can think of that declaration as a shorthand for: static void <T> reverse(List<T> list)
  • 55. Copyright © 2014 by John Wiley & Sons. All rights reserved. 55 Type Erasure In the Java virtual machine, generic types are erased.
  • 56. Copyright © 2014 by John Wiley & Sons. All rights reserved. 56 Type Erasure  The virtual machine erases type parameters, replacing them with their bounds or Objects. For example, generic class Pair<T, S> turns into the following raw class: public class Pair { private Object first; private Object second; public Pair(Object firstElement, Object secondElement) { first = firstElement; second = secondElement; } public Object getFirst() { return first; } public Object getSecond() { return second; } }
  • 57. Copyright © 2014 by John Wiley & Sons. All rights reserved. 57 Type Erasure  Same process is applied to generic methods.  In this generic method: public static <E extends Measurable> E min(E[] objects) { E smallest = objects[0]; for (int i = 1; i < objects.length; i++) { E obj = objects[i]; if (obj.getMeasure() < smallest.getMeasure()) { smallest = obj; } } return smallest; }
  • 58. Copyright © 2014 by John Wiley & Sons. All rights reserved. 58 Type Erasure  The type parameter Is replaced with its bound Measurable: public static Measurable min(Measurable[] objects) { Measurable smallest = objects[0]; for (int i = 1; i < objects.length; i++) { Measurable obj = objects[i]; if (obj.getMeasure() < smallest.getMeasure()) { smallest = obj; } } return smallest; }
  • 59. Copyright © 2014 by John Wiley & Sons. All rights reserved. 59 Type Erasure  Knowing about type erasure helps you understand limitations of Java generics.  You cannot construct new objects of a generic type.  For example, trying to fill an array with copies of default objects would be wrong: public static <E> void fillWithDefaults(E[] a) { for (int i = 0; i < a.length; i++) a[i] = new E(); // ERROR }  Type erasure yields: public static void fillWithDefaults(Object[] a) { for (int i = 0; i < a.length; i++) a[i] = new Object(); // Not useful }
  • 60. Copyright © 2014 by John Wiley & Sons. All rights reserved. 60 Type Erasure  To solve this particular problem, you can supply a default object: public static <E> void fillWithDefaults(E[] a, E defaultValue) { for (int i = 0; i < a.length; i++) a[i] = defaultValue; }
  • 61. Copyright © 2014 by John Wiley & Sons. All rights reserved. 61 Type Erasure  You cannot construct an array of a generic type: public class Stack<E> { private E[] elements; . . . public Stack() { elements = new E[MAX_SIZE]; // Error } }  Because the array construction expression new E[] would be erased to new Object[].
  • 62. Copyright © 2014 by John Wiley & Sons. All rights reserved. 62 Type Erasure  One remedy is to use an array list instead: public class Stack<E> { private ArrayList<E> elements; . . . public Stack() { elements = new ArrayList<E>(); // Ok } . . . }
  • 63. Copyright © 2014 by John Wiley & Sons. All rights reserved. 63 Type Erasure  Another solution is to use an array of objects and cast when reading elements from the array: public class Stack<E> { private Object[] elements; private int currentSize; . . . public Stack() { elements = new Object[MAX_SIZE]; // Ok } . . . public E pop() { size--; return (E) elements[currentSize]; } }  The cast (E) generates a warning because it cannot be checked at compile time
  • 64. Copyright © 2014 by John Wiley & Sons. All rights reserved. 64 Self Check 18.22 Answer: public static <E> Comparable<E> min(Comparable<E>[] objects) is an error. You cannot have an array of a generic type. 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?
  • 65. Copyright © 2014 by John Wiley & Sons. All rights reserved. 65 Self Check 18.23 Answer: public static void print(Object[] a) { for (Object e : a) { System.out.print(e + " "); } System.out.println(); } What is the erasure of the print method in Section 18.3?
  • 66. Copyright © 2014 by John Wiley & Sons. All rights reserved. 66 Self Check 18.24 Answer: This code compiles (with a warning), but it is a poor technique. In the future, if type erasure no longer happens, the code will be wrong. The cast from Object[] to String[] will cause a class cast exception. Could the Stack example be implemented as follows? public class Stack<E> { private E[] elements; . . . public Stack() { elements = (E[]) new Object[MAX_SIZE]; } . . . }
  • 67. Copyright © 2014 by John Wiley & Sons. All rights reserved. 67 Self Check 18.25 Answer: Internally, ArrayList uses an Object[] array. Because of type erasure, it can’t make an E[] array. The best it can do is make a copy of its internal Object[] array. The ArrayList<E> class has a method: Object[] toArray() Why doesn't the method return an E[]?
  • 68. Copyright © 2014 by John Wiley & Sons. All rights reserved. 68 Self Check 18.26 Answer: It can use reflection to discover the element type of the parameter a, and then construct another array with that element type (or just call the Arrays.copyOf method). 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.)
  • 69. Copyright © 2014 by John Wiley & Sons. All rights reserved. 69 Self Check 18.27 Answer: The method needs to construct a new array of type T. However, that is not possible in Java without reflection. Why can't the method static <T> T[] copyOf(T[] original, int newLength) be implemented without reflection?