Java Generics
Generics let you write classes and methods that work with any type while keeping full type safety. You have been using them since the ArrayList chapter: in List<String>, String is a type argument that tells the compiler what the list contains. In this chapter you'll write your own generic code.
Why generics?
Before generics (Java 5), collections stored plain Objects. You had to cast every element you took out, and mistakes only appeared at runtime:
List items = new ArrayList(); // raw type: holds anything
items.add("hello");
items.add(42); // compiles - oops
String s = (String) items.get(1); // ClassCastException at runtimeWith generics the compiler catches the error immediately, and no casts are needed:
List<String> items = new ArrayList<>();
items.add("hello");
items.add(42); // compile error: int cannot be converted to String
String s = items.get(0); // no castA generic class
Declare a type parameter in angle brackets after the class name. By convention it's a single capital letter: T (type), E (element), K/V (key/value).
class Box<T> {
private T content;
void put(T content) {
this.content = content;
}
T get() {
return content;
}
boolean isEmpty() {
return content == null;
}
}
class Main {
public static void main(String[] args) {
Box<String> letter = new Box<>();
letter.put("Dear Ada...");
String text = letter.get(); // no cast needed
System.out.println(text);
Box<Integer> coins = new Box<>();
System.out.println("empty: " + coins.isEmpty());
coins.put(250);
System.out.println(coins.get() + 50);
}
}Dear Ada...
empty: true
300
One class, Box, serves strings, integers and anything else — and each Box only accepts its own type.
Multiple type parameters
class Pair<A, B> {
private final A first;
private final B second;
Pair(A first, B second) {
this.first = first;
this.second = second;
}
A first() { return first; }
B second() { return second; }
<C> Pair<A, C> withSecond(C newSecond) {
return new Pair<>(first, newSecond);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
class Main {
public static void main(String[] args) {
Pair<String, Integer> score = new Pair<>("Kai", 87);
System.out.println(score);
System.out.println(score.first() + " scored " + score.second());
Pair<String, Boolean> passed = score.withSecond(score.second() >= 50);
System.out.println(passed);
}
}(Kai, 87)
Kai scored 87
(Kai, true)
Generic methods
A method can have its own type parameters, declared before the return type. The compiler infers the actual type from the arguments:
import java.util.List;
class Main {
static <T> T lastOf(List<T> list) {
return list.get(list.size() - 1);
}
static <T> void printAll(T[] items) {
for (T item : items) System.out.print(item + " ");
System.out.println();
}
public static void main(String[] args) {
String s = lastOf(List.of("red", "green", "blue"));
Integer n = lastOf(List.of(1, 2, 3));
System.out.println(s + " " + n);
printAll(new String[] {"a", "b", "c"});
printAll(new Double[] {1.5, 2.5});
}
}blue 3
a b c
1.5 2.5
Bounded type parameters
Sometimes the type must have certain capabilities. <T extends Comparable<T>> means "any type that can be compared to itself", so you may call compareTo. <T extends Number> allows calling doubleValue():
import java.util.List;
class Main {
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;
}
static <T extends Number> double average(List<T> numbers) {
double sum = 0;
for (T n : numbers) sum += n.doubleValue();
return sum / numbers.size();
}
public static void main(String[] args) {
System.out.println(max(List.of(4, 19, 7)));
System.out.println(max(List.of("pear", "apple", "zucchini")));
System.out.println(average(List.of(1, 2, 3, 4)));
System.out.println(average(List.of(2.5, 3.5)));
// average(List.of("a", "b")); // error: String is not a Number
}
}19
zucchini
2.5
3.0
Wildcards
The wildcard ? stands for "some unknown type". It's used in parameters to make methods accept a wider range of generic types:
| Syntax | Meaning | Typical use |
|---|---|---|
List<?> |
a list of anything | read elements as Object |
List<? extends Number> |
a list of Number or a subtype |
read numbers (producer) |
List<? super Integer> |
a list of Integer or a supertype |
write integers (consumer) |
import java.util.ArrayList;
import java.util.List;
class Main {
static double sum(List<? extends Number> nums) {
double total = 0;
for (Number n : nums) total += n.doubleValue();
return total;
}
static void fillWithOnes(List<? super Integer> target, int count) {
for (int i = 0; i < count; i++) target.add(1);
}
public static void main(String[] args) {
List<Integer> ints = List.of(1, 2, 3);
List<Double> doubles = List.of(0.5, 0.25);
System.out.println(sum(ints) + " " + sum(doubles));
List<Number> numbers = new ArrayList<>();
fillWithOnes(numbers, 3);
System.out.println(numbers);
}
}6.0 0.75
[1, 1, 1]
A helpful memory aid is PECS: Producer Extends, Consumer Super.
Note: A
List<Integer>is not aList<Number>, even thoughIntegeris aNumber. If it were, you could add aDoubleto a list of integers. Wildcards are the safe way to express "a list of some kind of number".
Test yourself
What is the main benefit of generics?
- Faster execution
- Type safety at compile time without casts
- Smaller class files
- Support for primitive types
What does <T extends Comparable<T>> allow inside the method?
- Calling compareTo on T values
- Only Strings as T
- Creating new T objects
- Using primitive types
Which parameter type accepts both List<Integer> and List<Double> for reading numbers?
- List<Number>
- List<Object>
- List<? extends Number>
- List<? super Number>