Why this matters
- Without generics every collection returns
Objectand every read needs a cast, so a wrong cast becomes a run-time crash instead of a compile error. - Wildcards look like syntax noise until you need to write a method that accepts "a list of any kind of number", and then they are the only answer.
- Erasure explains a handful of restrictions that otherwise seem arbitrary, and it is a reliable interview question.
The problem generics solve
The second version fails in your editor rather than in production. That is the entire value.
Generic classes and methods
A generic method declares its own type parameter before the return type, which lets it be used independently of the class.
Conventional parameter names
T— type. The default for a single parameter.E— element. Used throughout the collections.K,V— key and value, for maps.R— result, for a function's return type.N— number.
Bounded type parameters
extends on a type parameter means "this type or a subtype", and it unlocks the bound's methods
inside the class.
Multiple bounds are separated by &, with the class bound first if there is one:
Wildcards
A wildcard appears where you use a generic type rather than where you declare one. It is how you accept a family of parameterisations.
You know everything coming out is at least a Number.
You know the list can hold an Integer safely.
The guiding rule is PECS — Producer Extends, Consumer Super.
| Aspect | Wildcard | What you can do |
|---|---|---|
| List<? extends Number> | Read as Number — a producer | Cannot add anything except null |
| List<? super Integer> | Add Integer and its subtypes — a consumer | Reads come back as Object |
| List<?> | Read as Object, check size, clear | Cannot add anything except null |
| List<Object> | Read and write Object | Accepts only an actual List<Object> |
List<? extends Number>
WildcardRead as Number — a producerWhat you can doCannot add anything except nullList<? super Integer>
WildcardAdd Integer and its subtypes — a consumerWhat you can doReads come back as ObjectList<?>
WildcardRead as Object, check size, clearWhat you can doCannot add anything except nullList<Object>
WildcardRead and write ObjectWhat you can doAccepts only an actual List<Object>
If you read from the parameter use extends; if you write into it use super.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 10 sections
- Generics are not covariant
- Type erasure
- Bridge methods
- Generic arrays, heap pollution, and @SafeVarargs
- Comparable with ? super T (sorting bound)
- Reifiable types
- Type-safe heterogeneous container (Expert pattern)
- var with generics (Java 10+)
- Raw types
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.