Lecture8-1
Lecture8-1
Lecture 8-1
Generic Classes
Emily Navarro
Announcements
• Example: simple generic class that stores pairs of arbitrary objects such as:
Pair<String, Integer> result = new Pair<>("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: for a method that computes two values at the same time (method
returns a Pair<String, Integer>)
• Generic Pair class requires two type parameters, one for each element type
enclosed in angle brackets:
public class Pair<T, S>
T General type
• Place the type variables for a generic class after the class name, enclosed in angle
brackets (< and >)
public class Pair<T, S>
• 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[]
• 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;
• 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
}
• 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