Generics, bounded types and wildcards
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
The problem generics solve
You have used List<String> since the collections lesson. Before generics, a List held Object. You cast on the way out, and a wrong cast failed at runtime. With generics, the compiler checks the types and you never cast. This lesson shows how to write generic code yourself.
A generic class
A type parameter is declared in angle brackets after the class name. By convention it is a single capital letter: T for a type, E for an element, K and V for key and value.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
// A generic class
Box<String> label = new Box<>("fragile");
Box<Integer> count = new Box<>(12);
String text = label.get(); // no cast needed
int n = count.get();
System.out.println(text + " " + n);
// A generic record with two type parameters
Pair<String, Integer> pair = new Pair<>("age", 34);
System.out.println(pair.key() + "=" + pair.value() + " " + pair.swap());
// A generic method with a bound
System.out.println(max(List.of(3, 9, 4)));
System.out.println(max(List.of("pear", "apple", "zebra")));
// Mapping with two type parameters
List<Integer> lengths = map(List.of("a", "bbb", "cc"), String::length);
System.out.println(lengths);
// Wildcards
List<Integer> ints = List.of(1, 2, 3);
List<Double> doubles = List.of(1.5, 2.5);
System.out.println(sum(ints) + " " + sum(doubles));
List<Object> sink = new ArrayList<>();
addNumbers(sink);
System.out.println(sink);
// The compiler stops mistakes
// label.set(5); // does not compile: Box<String> cannot hold an int
}
static class Box<T> {
private T value;
Box(T value) { this.value = value; }
T get() { return value; }
void set(T value) { this.value = value; }
}
record Pair<A, B>(A key, B value) {
Pair<B, A> swap() {
return new Pair<>(value, key);
}
}
// T must be comparable with itself
static <T extends Comparable<T>> T max(List<T> items) {
if (items.isEmpty()) {
throw new IllegalArgumentException("no items");
}
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
static <T, R> List<R> map(List<T> source, Function<T, R> mapper) {
List<R> result = new ArrayList<>();
for (T item : source) {
result.add(mapper.apply(item));
}
return result;
}
// "? extends Number": we can read Numbers out of it
static double sum(List<? extends Number> numbers) {
double total = 0;
for (Number number : numbers) {
total += number.doubleValue();
}
return total;
}
// "? super Integer": we can put Integers into it
static void addNumbers(List<? super Integer> target) {
for (int i = 1; i <= 3; i++) {
target.add(i);
}
}
}
Walking through it
Box<T> stores a value of whatever type you choose when you use it. Box<String> and Box<Integer> are checked separately. The diamond new Box<>("fragile") lets the compiler infer the type argument. The commented-out line, label.set(5), would not compile, and that is the whole point: the error is found before the program runs.
The Pair record has two type parameters. Its swap method returns a pair with the types reversed. Records and interfaces can be generic in the same way as classes.
The method max declares its own type parameter before the return type: <T extends Comparable<T>>. The bound extends Comparable<T> says that T must be able to compare itself with other T values. Without the bound, the compiler would not let us call compareTo. The same method works for Integer and String, because both are comparable. If you pass a type that is not comparable, you get a compile error.
The map method has two type parameters and uses Function<T, R> from the standard library. The compiler infers both from the arguments. You will meet this same shape in the stream API.
Wildcards
A surprise for newcomers: List<Integer> is not a subtype of List<Number>, even though Integer is a subtype of Number. If it were, you could pass a list of integers to a method that adds a Double to it, and corrupt the list. Wildcards solve the practical cases.
List<? extends Number>means "a list of some subtype of Number". You can read numbers from it, but you cannot add to it. Use it for parameters that you only read from, as insum.List<? super Integer>means "a list of Integer or a supertype of it". You can add integers to it. Use it for parameters that you write into, as inaddNumbers.
The memory aid is PECS: Producer Extends, Consumer Super. If the collection produces values for you, use extends. If it consumes values from you, use super. The sorting method Collections.sort and the Comparator API use this pattern a lot.
Type erasure
Generics exist at compile time. After compiling, the type arguments are erased, and the compiled code works with Object and inserts casts for you. This was done to stay compatible with older code. It has consequences. You cannot write new T(), you cannot create a generic array with new T[10], you cannot use instanceof List<String>, and you cannot use primitive types as type arguments. Use Integer, not int.
Common mistakes
- Using raw types. Writing
Listwithout a type argument turns off the checks. Always give the argument. - Trying to add to a
List<? extends X>. The compiler rejects it, correctly. - Over-engineering with generics. If a class only ever holds
Orderobjects, make it non-generic. - Forgetting the bound and then casting inside the method.
- Expecting
List<Integer>to be aList<Number>.
Try it yourself
- Write a generic
Stack<T>class backed by anArrayList<T>, withpush,popandpeek. - Write a generic method
swap(T[] array, int i, int j). - Write
static void printAll(List<?> items)that prints every item, and call it with lists of different types.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
// A generic class
Box<String> label = new Box<>("fragile");
Box<Integer> count = new Box<>(12);
String text = label.get(); // no cast needed
int n = count.get();
System.out.println(text + " " + n);
// A generic record with two type parameters
Pair<String, Integer> pair = new Pair<>("age", 34);
System.out.println(pair.key() + "=" + pair.value() + " " + pair.swap());
// A generic method with a bound
System.out.println(max(List.of(3, 9, 4)));
System.out.println(max(List.of("pear", "apple", "zebra")));
// Mapping with two type parameters
List<Integer> lengths = map(List.of("a", "bbb", "cc"), String::length);
System.out.println(lengths);
// Wildcards
List<Integer> ints = List.of(1, 2, 3);
List<Double> doubles = List.of(1.5, 2.5);
System.out.println(sum(ints) + " " + sum(doubles));
List<Object> sink = new ArrayList<>();
addNumbers(sink);
System.out.println(sink);
// The compiler stops mistakes
// label.set(5); // does not compile: Box<String> cannot hold an int
}
static class Box<T> {
private T value;
Box(T value) { this.value = value; }
T get() { return value; }
void set(T value) { this.value = value; }
}
record Pair<A, B>(A key, B value) {
Pair<B, A> swap() {
return new Pair<>(value, key);
}
}
// T must be comparable with itself
static <T extends Comparable<T>> T max(List<T> items) {
if (items.isEmpty()) {
throw new IllegalArgumentException("no items");
}
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
static <T, R> List<R> map(List<T> source, Function<T, R> mapper) {
List<R> result = new ArrayList<>();
for (T item : source) {
result.add(mapper.apply(item));
}
return result;
}
// "? extends Number": we can read Numbers out of it
static double sum(List<? extends Number> numbers) {
double total = 0;
for (Number number : numbers) {
total += number.doubleValue();
}
return total;
}
// "? super Integer": we can put Integers into it
static void addNumbers(List<? super Integer> target) {
for (int i = 1; i <= 3; i++) {
target.add(i);
}
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account