A type parameter lets one algorithm preserve the caller's element type without unsafe casts.
Build a Complete Mental Model
Generics provide compile-time type safety and reusable algorithms. Java generics are invariant; use producer extends and consumer super (PECS), and account for runtime limitations caused by type erasure.
Apply It in Real Java
Write a generic `first` method and a copy method using bounds and wildcards, then verify compiler diagnostics for raw types and invalid assignments.
After This Lesson
import java.util.List;
class Main {
static <T> T first(List<T> values) {
if (values.isEmpty()) throw new IllegalArgumentException("empty list");
return values.getFirst();
}
public static void main(String[] args) {
String name = first(List.of("Ada", "Linus"));
System.out.println(name);
}
}AdaTry It Yourself
Write a generic `first` method and a copy method using bounds and wildcards, then verify compiler diagnostics for raw types and invalid assignments.
Common Mistake
Assuming `List<Integer>` is a subtype of `List<Number>` or hiding type problems with raw types.