Module 9 · Collections and Generics — topic 4 of 5
Generics
Type parameters for classes, interfaces and methods, type safety without casts, bounded types, wildcards (? extends, ? super), the PECS rule, and type erasure.
Learning objectives
- Write generic classes and generic methods
- Use bounded type parameters and wildcards
- Explain type erasure and its limitations
Definition
Generics let classes, interfaces and methods be parameterised by types, so the same code works with many types while the compiler checks type safety. A type parameter such as <T> is replaced by a concrete type argument when the generic is used.
Introduction
Before Java 5, collections held plain Objects: you had to cast everything you took out and hope it was the right type. Generics move those checks to compile time. List<String> can only contain strings, and get returns a String — no casts and no ClassCastException surprises.
Why it matters
Every collection and much of the standard library is generic; reading their signatures requires understanding generics.
Writing your own generic utilities (a Pair, a cache, a repository) lets you reuse code safely.
Detailed explanation
Generic classes. class Box<T> { private T value; T get() { ... } }. T is a type parameter; Box<String> and Box<Integer> are parameterised types. By convention: T (type), E (element), K and V (key and value), R (result).
Generic methods declare their own type parameters before the return type: static <T> T firstOrDefault(List<T> list, T fallback). The compiler usually infers T from the arguments.
Bounded types. <T extends Comparable<T>> accepts only types that can be compared, so the method may call compareTo. <T extends Number> allows doubleValue().
Invariance. A List<Integer> is *not* a List<Number>, even though Integer is a Number — otherwise you could add a Double to a list of Integers.
Wildcards. List<? extends Number> means 'a list of some subtype of Number': you can read Numbers from it but not add (except null). List<? super Integer> means 'a list of Integer or a supertype': you can add Integers but reading gives only Object. The rule of thumb PECS: *Producer Extends, Consumer Super*. List<?> is a list of unknown type.
Type erasure. Generic type information is checked at compile time and then erased: at run time a List<String> is just a List. Consequently you can't write new T(), new T[n], instanceof List<String>, or use primitives as type arguments (use Integer).
Syntax
- Use the diamond:
new Pair<>("a", 1). - Primitive types can't be type arguments; use wrappers.
- Generic code compiles with no casts at the call site.
Code examples
A generic class and method
Asha will be 22 x -1 Pair[first=pi, second=3.14159] swapped Pair[first=3.14159, second=pi]
Bounded type parameters
17 zucchini 2.5 3.0
More examples
Wildcards, PECS and a generic repository
6.0 2.0 [1, 4, 9, 1, 2, 3] [1, 4] Head First Java, missing: false [Book[isbn=978-1, title=Effective Java, year=2018], Book[isbn=978-2, title=Head First Java, year=2022]] same runtime class: true
Step-by-step explanation
sum(Collection<? extends Number>)accepts a List<Integer> or a List<Double> because it only *reads* Numbers — a producer, soextends.addSquares(Collection<? super Integer>)accepts a List<Number> or List<Object> because it only *writes* Integers — a consumer, sosuper.copycombines both: read Ts from a producer, write them to a consumer.Repository<K, V>works for any value type; it is told how to extract the key with a function (Book::isbn) and returnsOptional<V>instead of null.- Because of type erasure,
ArrayList<String>andArrayList<Integer>share one runtime class.
Expected output
Running “Wildcards, PECS and a generic repository” prints exactly:
Practical applications
- Collections, Optional, Stream and Comparator are all generic
- Generic DAOs and repositories in Spring Data
- Utility methods such as Collections.max and Collections.sort
- Typed result wrappers such as Result<T> or Page<T>
Best practices
- Never use raw types in new code.
- Follow PECS when choosing wildcards for parameters.
- Prefer generic methods and bounded types over casting.
Common mistakes
Using raw types
Avoid
Prefer
Raw types turn off generic checking; mistakes are only discovered at run time.
Expecting List<Integer> to be a List<Number>
Avoid
Prefer
Generic types are invariant; use a wildcard to accept lists of any Number subtype.
Important notes
- Type erasure is why Java can't create generic arrays (
new T[10]); use a List<T> or pass a Class<T>. - Generic methods can have explicit type arguments when inference fails:
List.<Integer>of().
Key takeaways
- Generics add compile-time type safety and remove casts.
- Bounds (extends) restrict type parameters; wildcards make parameters flexible.
- PECS: producers use extends, consumers use super; types are erased at run time.
Try it yourself
- 1Write a generic
Stack<T>class backed by an ArrayList with push, pop and peek. - 2Write
static <K, V extends Comparable<V>> K keyOfMax(Map<K, V> map).
Finished reading? Mark it complete to update your dashboard.
Suggested practice
6 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhy can't you write `List<int>`?
- ModerateWhy doesn't `List<Number> nums = new ArrayList<Integer>();` compile?
- ModerateFollowing PECS, which parameter type suits a method that only ADDS Integers to a list?