Introduction
You have already used generics: List<String> and Map<String, Integer> are generic types, where the angle brackets say what the collection holds. Generics are why names.get(0) is known to be a String with no cast, and why names.add(42) is a compile error. This lesson shows how to write your own generic classes and methods.
How it works
A generic class declares type parameters after its name:
class Box<T> {
private T value;
Box(T value) { this.value = value; }
T get() { return value; }
}
Box<String> b = new Box<>("hi"); // T is String
String s = b.get(); // no cast
Inside the class, T is used like any type. Each use chooses the real type, and the diamond operator <> lets Java infer it from the variable. A class can have several parameters, as in Pair<A, B>. Type arguments must be classes, so a box of numbers is Box<Integer>.
A generic method declares its own type parameter before the return type: static <T> T first(List<T> items). Java infers T from the argument, so first(List.of(1, 2)) returns an Integer.
Inside generic code, Java knows nothing about T, so you can only call methods every object has. A bound promises more: <T extends Comparable<T>> means T can be compared with itself, so the method may call compareTo. Strings, numbers and dates all qualify.
Wildcards make parameters flexible. A List<Integer> is not a List<Number>, even though an Integer is a Number, because otherwise a Double could be added to a list of integers. A method that only reads numbers can accept List<? extends Number>, which matches lists of Integer, Double or any other Number. List<? super Integer> matches lists that can accept Integers. The rule of thumb: "extends" for reading, "super" for writing.
Generics exist only at compile time: the compiled code uses plain objects (type erasure), which is why new T() and instanceof List<String> are not allowed.
Example
import java.util.*;
public class Main {
// A generic class: A and B are filled in when a Pair is created.
static class Pair<A, B> {
private final A first;
private final B second;
Pair(A first, B second) {
this.first = first;
this.second = second;
}
A getFirst() { return first; }
B getSecond() { return second; }
Pair<B, A> swap() {
return new Pair<>(second, first);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
// A generic method with a bound: T must be comparable with itself.
static <T extends Comparable<T>> T largest(List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
public static void main(String[] args) {
Pair<String, Integer> score = new Pair<>("Rina", 92);
Pair<Integer, String> swapped = score.swap();
System.out.println(score + " " + swapped);
int doubled = score.getSecond() * 2; // no cast needed
System.out.println(doubled);
System.out.println(largest(List.of(4, 17, 9)) + " " + largest(List.of("pear", "apple", "fig")));
}
}Line by line
Pair<A, B>stores two values of any two types;swapreturns aPair<B, A>.scoreis aPair<String, Integer>, sogetSecond()returns an Integer that can be doubled with no cast.largestworks for any comparable type: once for integers, once for strings.
Expected result
(Rina, 92) (92, Rina)
184
17 pear
In the real world
The whole collections framework is generic, and so are many library APIs: Optional<T>, CompletableFuture<T>, repositories such as Repository<User, Long> in Spring. Writing a small generic class, such as a result type or a cache, removes duplicated code and casts from an application.
Common mistakes
- Using raw types such as
Listwithout a type argument, which turns off the checks. - Expecting
List<Integer>to be aList<Number>; use a wildcard. - Calling methods on T without a bound; the compiler only knows it is an Object.
- Trying new T() or a primitive type argument such as
Box<int>.
Best practices
- Always give type arguments, using the diamond operator on the right.
- Add the narrowest bound that the code needs.
- Use
? extendsfor parameters you only read from and? superfor those you only write to.
Summary
Generic classes and methods take type parameters, chosen at each use and often inferred with the diamond operator, so code works for many types without casts or lost type checks. Bounds such as T extends Comparable<T> allow calling methods on T, wildcards accept related types, and type information exists only at compile time.
Quick check
Key takeaways
- Generics let one class or method work with many types and still catch type errors at compile time.
- A bound such as T extends Comparable<T> lets the code call compareTo on T.
- Wildcards make methods accept related types, such as any list of numbers.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.