Lesson content
Read, practise, then check your understanding
Generics move type mistakes from runtime to compilation. Type parameters appear on classes, interfaces, and methods; bounds state required capabilities.
Bounds and variance
static double total(List<? extends Number> values) {
double sum = 0;
for (Number value : values) sum += value.doubleValue();
return sum;
}
static void addDefaults(List<? super Integer> target) {
target.add(0);
}
Generic types are invariant: List<Integer> is not List<Number>. Follow PECS—producer extends, consumer super. Java implements most generics through type erasure, so type arguments are usually unavailable at runtime, primitives cannot be direct arguments, and creating new T() or new T[] is restricted. Avoid raw types and unchecked casts; prefer bounded APIs that express the operations truly needed.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.