Generics in Java
Generics let a class or method work with many types while the compiler still checks that you use them consistently: a List
Contents
Why generics exist
Before Java 5, collections held ObjectEList<E>List<String>
| Term | Example | Meaning |
|---|---|---|
| Generic type | class Box<T> | A class or interface with type parameters |
| Parameterized type | Box<String> | A generic type with its type arguments filled in |
| Generic method | <T> T max(List<T> items) | A method with its own type parameter, usually inferred |
| Bounded type parameter | <T extends Number> | T must be Number |
| Wildcard | List<?>List<? extends Number> | "Some type" that the code does not name |
| Raw type | List | A generic type used without arguments; exists only for old code |
| Erasure | Type arguments are removed after compilation |
By convention, type parameters are single capital letters: TEKVR
Generic classes, generic methods and raw types
The program defines a generic BoxmaxListmax
import java.util.ArrayList;
import java.util.List;
public class WhyGenerics {
// A generic class: T is chosen by whoever creates a Box
static class Box<T> {
private T value;
void put(T value) {
this.value = value;
}
T get() {
return value;
}
}
// A generic method: T is inferred from the arguments
static <T extends Comparable<T>> T max(List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
@SuppressWarnings({"rawtypes", "unchecked"})
static void rawTypeProblem() {
List raw = new ArrayList(); // no type argument: a raw type
raw.add("text");
raw.add(42); // nothing stops this
try {
for (Object o : raw) {
String s = (String) o; // the cast fails at run time
System.out.println("raw list item: " + s);
}
} catch (ClassCastException e) {
System.out.println("raw list: ClassCastException on the second element");
}
}
public static void main(String[] args) {
Box<String> names = new Box<>();
names.put("Ada");
String n = names.get(); // no cast needed
System.out.println("box holds " + n);
// names.put(42); would not compile: 42 is not a String
System.out.println("max of numbers: " + max(List.of(3, 17, 8)));
System.out.println("max of words: " + max(List.of("pear", "apple", "plum")));
rawTypeProblem();
}
}
Output:
box holds Ada
max of numbers: 17
max of words: plum
raw list item: text
raw list: ClassCastException on the second element
returns aBox<String> fromString with no cast, andget would be a compile error, not a run-time surprise.names.put(42) declares its own type parameter,max . The bound says T must be comparable to itself, which is what lets the body call<T extends Comparable<T>> . The compiler inferred T ascompareTo for the first call andInteger for the second.String- The raw
accepted both a string and the number 42; the cast failed only when the list was read. That is the pre-Java 5 situation generics were designed to remove. javac warns about raw types withList ; the method suppresses the warning to show the problem.-Xlint:rawtypes
The rules javac enforces
Generics are checked by the compiler, and some things that look natural are not allowed. The program compiles a class that breaks seven rules and prints javac's errors; the numbers in the source comments help match each error to its line.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.tools.ToolProvider;
// Compiles code that breaks the rules of generics and prints javac's errors
public class GenericRules {
static final String SOURCE = """
import java.util.ArrayList;
import java.util.List;
class Rules<T> {
static T shared; // 1: static field of type T
T make() { return new T(); } // 2: new T()
T[] array() { return new T[10]; } // 3: generic array creation
boolean check(Object o) { return o instanceof T; } // 4: instanceof T
void variance(List<Integer> ints, List<? extends Number> nums) {
List<Number> n = ints; // 5: not a subtype
nums.add(Integer.valueOf(1)); // 6: cannot add to ? extends
}
List<int> primitives; // 7: primitive type argument
}
""";
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("generics");
Path file = dir.resolve("Rules.java");
Files.writeString(file, SOURCE);
ByteArrayOutputStream err = new ByteArrayOutputStream();
ToolProvider.getSystemJavaCompiler().run(null, null,
new PrintStream(err, true, StandardCharsets.UTF_8),
"-d", dir.toString(), file.toString());
err.toString(StandardCharsets.UTF_8).lines()
.filter(l -> l.startsWith(file.toString()))
.map(l -> l.substring(dir.toString().length() + 1))
.map(l -> l.length() > 98 ? l.substring(0, 95) + "..." : l)
.forEach(System.out::println);
}
}
Output:
Rules.java:5: error: non-static type variable T cannot be referenced from a static context
Rules.java:15: error: unexpected type
Rules.java:6: error: unexpected type
Rules.java:7: error: generic array creation
Rules.java:8: error: Object cannot be safely cast to T
Rules.java:11: error: incompatible types: List<Integer> cannot be converted to List<Number>
Rules.java:12: error: incompatible types: Integer cannot be converted to CAP#1
- Line 5: a
field cannot have typestatic , because there is one static field per class, shared byT andRules<String> .Rules<Integer> - Line 6:
is impossible: at run time T is erased, so the JVM would not know which class to create. Pass anew T() (for exampleSupplier<T> ) or aBox::new instead.Class<T> - Line 7: "generic array creation": an array must know its element type at run time, which T cannot provide. Use a
, or let the caller pass an array, asList<T> does.Collection.toArray(T[]) - Line 8:
cannot be checked for the same reason.instanceof T - Line 11: a
is not aList<Integer> , even though everyList<Number> is aInteger . If it were, code could add aNumber to the list of integers through theDouble reference. Generic types are invariant; arrays, which are covariant, check this only at run time withList<Number> .ArrayStoreException - Line 12: nothing can be added to a
, because the list might really be aList<? extends Number> . javac names the unknown typeList<Double> ("capture of ?").CAP#1 - Line 15: type arguments must be reference types:
is not allowed, which is whyList<int>autoboxing exists.
Wildcards and PECS
Because generic types are invariant, a method that takes List<Number>List<Integer>
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class Wildcards {
// ? extends Number: read Numbers from it (a producer)
static double sum(Collection<? extends Number> numbers) {
double total = 0;
for (Number n : numbers) {
total += n.doubleValue();
}
return total;
}
// ? super Integer: write Integers into it (a consumer)
static void addRange(List<? super Integer> target, int count) {
for (int i = 1; i <= count; i++) {
target.add(i);
}
}
// ? alone: the method does not care about the element type
static int countNulls(Collection<?> items) {
int nulls = 0;
for (Object o : items) {
if (o == null) {
nulls++;
}
}
return nulls;
}
public static void main(String[] args) {
List<Integer> ints = List.of(1, 2, 3);
List<Double> doubles = List.of(1.5, 2.5);
System.out.println("sum ints: " + sum(ints) + ", sum doubles: " + sum(doubles));
List<Number> numbers = new ArrayList<>();
List<Object> objects = new ArrayList<>();
addRange(numbers, 3);
addRange(objects, 2);
System.out.println("into List<Number>: " + numbers);
System.out.println("into List<Object>: " + objects);
System.out.println("nulls: " + countNulls(Arrays.asList("a", null, "b", null)));
// List<Integer> is NOT a List<Number>, even though Integer is a Number
// List<Number> bad = ints; would not compile
List<? extends Number> ok = ints; // a read-only view of "some Number type"
System.out.println("first via wildcard: " + ok.get(0));
}
}
Output:
sum ints: 6.0, sum doubles: 4.0
into List<Number>: [1, 2, 3]
into List<Object>: [1, 2]
nulls: 2
first via wildcard: 1
accepted both asum(Collection<? extends Number>) and aList<Integer> : everything read from it is at least aList<Double> .Number accepted aaddRange(List<? super Integer>) and aList<Number> : any list that can hold anList<Object> is fine to write into.Integer accepts any collection when the code only needsCollection<?> methods, such as checking forObject .null- The rule of thumb is PECS, "producer extends, consumer super": a parameter you read from uses
, a parameter you write into uses? extends T , and one you both read and write uses plain? super T .T is the textbook example.Collections.copy(List<? super T> dest, List<? extends T> src)
Bounds, Comparable super T> and inference
Bounds restrict which type arguments are allowed. The program uses an AppleComparable<Fruit>
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
public class BoundsAndInference {
static class Fruit implements Comparable<Fruit> {
final int weight;
Fruit(int weight) {
this.weight = weight;
}
@Override
public int compareTo(Fruit other) {
return Integer.compare(weight, other.weight);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + weight + ")";
}
}
static class Apple extends Fruit { // an Apple is Comparable<Fruit>, not <Apple>
Apple(int weight) {
super(weight);
}
}
// Accepts Apple, because Apple implements Comparable<Fruit> and Fruit is a supertype
static <T extends Comparable<? super T>> T heaviest(List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
// Two bounds: T must be a Number AND Comparable
static <T extends Number & Comparable<T>> double spread(List<T> values) {
return Collections.max(values).doubleValue() - Collections.min(values).doubleValue();
}
// A generic record and a generic method that changes the type parameter
record Pair<A, B>(A first, B second) {
<C> Pair<A, C> mapSecond(Function<? super B, ? extends C> f) {
return new Pair<>(first, f.apply(second));
}
}
public static void main(String[] args) {
List<Apple> apples = List.of(new Apple(150), new Apple(210), new Apple(180));
System.out.println("heaviest apple: " + heaviest(apples));
System.out.println("Collections.max: " + Collections.max(apples));
System.out.println("spread of ints: " + spread(List.of(4, 19, 7)));
Pair<String, Integer> p = new Pair<>("width", 1920); // diamond infers types
Pair<String, String> q = p.mapSecond(px -> px / 96 + " inches");
System.out.println(p + " -> " + q);
// Inference needs a hint when nothing tells it the type
List<String> empty = Collections.emptyList(); // inferred from target
var explicit = Collections.<String>emptyList(); // type witness
System.out.println("empty lists: " + empty + " " + explicit);
}
}
Output:
heaviest apple: Apple(210)
Collections.max: Apple(210)
spread of ints: 15.0
Pair[first=width, second=1920] -> Pair[first=width, second=20 inches]
empty lists: [] []
implementsApple , notComparable<Fruit> . With the boundComparable<Apple> , as in the earlierT extends Comparable<T> , calling it with amax does not compile: javac reports "method max cannot be applied to given types". The boundList<Apple> accepts any type comparable to itself or to a supertype, soT extends Comparable<? super T> found the 210 g apple. This is whyheaviest has that strange-looking signature.Collections.max requires both: the method can call<T extends Number & Comparable<T>> and pass the list todoubleValue() . A class bound, if any, must come first.Collections.max- The diamond
(Java 7) inferrednew Pair<>(...) from the variable's type.<String, Integer> introduced a new type parameter C, inferred from the lambda's result, to turn amapSecond into aPair<String, Integer> .Pair<String, String> - When there is nothing to infer from, as with
, the result would be avar x = Collections.emptyList() . A type witness,List<Object> , states the type explicitly.Collections.<String>emptyList()
Erasure: what is left at run time
Generics are implemented by type erasure: the compiler checks the types, then replaces each type parameter by its bound (Object
import java.util.ArrayList;
import java.util.List;
public class Erasure {
// Type arguments exist only at compile time
static <T> T[] toArray(List<T> list, T[] target) {
return list.toArray(target); // new T[] is impossible, so the caller passes an array
}
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
List<Integer> integers = new ArrayList<>();
boolean same = strings.getClass() == integers.getClass();
System.out.println("same class at run time: " + same);
System.out.println("class: " + strings.getClass().getName());
// instanceof List<String> is not allowed; only List<?> can be checked
Object o = strings;
System.out.println("o instanceof List<?>: " + (o instanceof List<?>));
strings.add("x");
String[] arr = toArray(strings, new String[0]);
System.out.println("array type: " + arr.getClass().getSimpleName());
}
}
Output:
same class at run time: true
class: java.util.ArrayList
o instanceof List<?>: true
array type: String[]
andList<String> are the same class at run time,List<Integer> . The type arguments are not stored in the objects.java.util.ArrayList is allowed because it asks only "is it ainstanceof List<?> ?", which the JVM can answer.List- Since T is erased,
asks the caller for an array of the right type and uses its class to create the result: a realtoArray .String[] - Erasure was chosen so that generic code and pre-Java 5 code could run together without changing the JVM. Its consequences, including bridge methods, unchecked casts and heap pollution, are on the
type erasure page . Generic information is still kept in class files for declarations, so reflection can read the declared type of a field such as .List<String> names
Guidelines
| Situation | Use |
|---|---|
| A method parameter you only read from | ? extends T |
| A method parameter you only write into | ? super T |
| Return types | Concrete types, never wildcards; callers should not have to deal with ? |
| Sorting or comparing elements | <T extends Comparable<? super T>>Comparator<? super T> |
| Creating instances of T | Take a Supplier<T>Class<T> |
| Arrays of T | Use List<T> |
| Raw types | Never in new code; fix the rawtypesunchecked |
| Generic varargs methods | Mark safe ones @SafeVarargs |