25 Generics
25 Generics
1
Parametric polymorphism
• parametric polymorphism: Ability for a function or type to be
written in such a way that it handles values identically without
depending on knowledge of their types.
Such a function or type is called a generic function or data type.
// in Java 1.4:
ArrayList names = new ArrayList();
names.add("Marty Stepp");
names.add("Stuart Reges");
String teacher = (String) names.get(0);
3
Type Parameters (Generics)
List<Type> name = new ArrayList<Type>();
4
Implementing generics
// a parameterized (generic) class
public class name<Type> {
or
public class name<Type, Type, ..., Type> {
By putting the Type in < >, you are demanding that any client that
constructs your object must supply a type parameter.
• You can require multiple type parameters separated by commas.
The rest of your class's code can refer to that type by name.
• The convention is to use a 1-letter name such as:
T for Type, E for Element, N for Number, K for Key, or V for Value.
5
Generics and arrays (15.4)
public class Foo<T> {
private T myField; // ok
private T[] myArray; // ok
6
Generics/arrays, fixed
public class Foo<T> {
private T myField; // ok
private T[] myArray; // ok
@SuppressWarnings("unchecked")
public Foo(T param) {
myField = param; // ok
T[] a2 = (T[]) (new Object[10]); // ok
}
}
But you can create variables of that type, accept them as parameters,
return them, or create arrays by casting Object[].
• Casting to generic types is not type-safe, so it generates a warning.
7
Comparing generic objects
public class ArrayList<E> {
...
public int indexOf(E value) {
for (int i = 0; i < size; i++) {
// if (elementData[i] == value) {
if (elementData[i].equals(value)) {
return i;
}
}
return -1;
}
}
8
A generic interface
// Represents a list of values.
public interface List<E> {
public void add(E value);
public void add(int index, E value);
public E get(int index);
public int indexOf(E value);
public boolean isEmpty();
public void remove(int index);
public void set(int index, E value);
public int size();
}
9
Generic methods
public static <Type> returnType name(params) {
• When you want to make just a single (often static) method generic
in a class, precede its return type by type parameter(s).
public class Collections {
...
public static <T> void copy(List<T> dst, List<T> src) {
for (T t : src) {
dst.add(t);
}
}
}
10
Bounded type parameters
<Type extends SuperType>
An upper bound; accepts the given supertype or any of its subtypes.
Works for multiple superclass/interfaces with & :
<Type extends ClassA & InterfaceB & InterfaceC & ...>
• Example:
// tree set works for any comparable type
public class TreeSet<T extends Comparable<T>> {
...
}
11
Complex bounded types
• public static <T extends Comparable<T>>
T max(Collection<T> c)
Find max value in any collection, if the elements can be compared.
12
Generics and subtyping
• Is List<String> a subtype of List<Object>?
• Is Set<Giraffe> a subtype of Collection<Animal>?
13
Wildcards
• ? indicates a wild-card type parameter, one that can be any type.
List<?> list = new List<?>(); // anything
14
Type erasure
• All generics types become type Object once compiled.
One reason: Backward compatibility with old byte code.
At runtime, all generic instantiations have the same type.
15
Generics and casting
• Casting to generic type results in a warning.
List<?> l = new ArrayList<String>(); // ok
List<String> ls = (List<String>) l; // warn
16