Java Generics and Wildcards
Understand Java generic invariance, upper and lower bounded wildcards, PECS, generic methods, and type erasure with examples.
Java generics catch many type errors at compile time, but generic types are invariant: a List<Integer> is not a List<Number>. Wildcards let APIs accept related types safely. This guide explains upper and lower bounds, the producer-extends/consumer-super rule, generic methods, and type erasure.
Why List<Integer> is not List<Number>
Integer is a subtype of Number, but Java does not make List<Integer> a subtype of List<Number>. If it did, a method receiving a list of Numbers could add a Double to a list that was originally declared as holding only Integers. Invariance prevents that unsafe substitution.
List<Integer> integers = new ArrayList<>();
// Does not compile:
// List<Number> numbers = integers;Wildcards express a limited relationship when a method needs to read from or write to different parameterized types.
Use an upper bound to read values
? extends Number means an unknown type that is Number or a subtype of Number. A method can safely read those elements as Numbers, but generally cannot add a specific Number because the actual list might be a List<Integer> or another narrower type.
static double sum(List<? extends Number> values) {
double total = 0;
for (Number value : values) {
total += value.doubleValue();
}
return total;
}This is useful for a producer of values consumed by the method. The method receives values from the collection, so the wildcard widens what it can accept while preserving safe reads.
Use a lower bound to add values
? super Integer means an unknown type that is Integer or one of its supertypes. You can safely add Integers to that collection, but when reading an element the compile-time type is only guaranteed to be Object:
static void addDefaults(List<? super Integer> destination) {
destination.add(10);
destination.add(20);
}This pattern is useful when the collection is a consumer that receives values. It can accept List<Integer>, List<Number>, or List<Object>.
Remember PECS, then check the whole method
A common mnemonic is PECS: Producer Extends, Consumer Super. If an argument only supplies T values, consider ? extends T. If it only accepts T values, consider ? super T. Use an exact type parameter when the method both reads and writes the same collection, or when the type relationship needs to connect multiple arguments.
static <T> void copy(
List<? super T> destination,
List<? extends T> source) {
for (T item : source) {
destination.add(item);
}
}The source produces T values and the destination consumes them. The method-level type parameter T connects the two wildcards. PECS is a design aid, not a rule to put wildcards on every generic type. Prefer the simplest signature that matches the operations the method performs.
Know when a type parameter is clearer
Wildcards are helpful for flexible parameters, but they can make return types harder for callers. A named type parameter can express relationships among multiple inputs and outputs:
static <T> T firstOrDefault(List<T> values, T fallback) {
return values.isEmpty() ? fallback : values.get(0);
}Here both the list elements and fallback share one type T. A wildcard would lose that connection. Use a named type variable when the method needs to refer back to the same type in more than one place.
Type erasure and runtime limits
Java implements generics with type erasure: parameterized types and type variables are mapped to non-parameterized types as part of compilation. Generic type checks provide compile-time safety, but most concrete type arguments are not available for ordinary runtime tests. For example, Java does not allow value instanceof List<String> because that parameterized type is not reifiable.
Avoid raw types in new code. They bypass generic checks and can move a type error to a later cast. When interoperating with legacy APIs, confine raw values to a small boundary and convert them to a typed representation as soon as possible.
Common mistakes
- Assuming subtype relationships automatically apply to generic containers.
- Trying to add a specific value to a
? extends Tcollection. - Reading from a
? super Tcollection as though the result were a T rather than Object. - Using wildcards in public return types when a named type parameter would be easier for callers.
- Expecting generic type arguments to be fully available at runtime.
Practical checklist
- List the operations the method needs: read, write, or both.
- For a read-only producer, consider
? extends T. - For a write-only consumer, consider
? super T. - Use a named type parameter when multiple arguments or the return value must share the same type.
- Keep raw types out of new APIs, and rely on compile-time checking rather than unsafe casts.
Wildcards make generic APIs more flexible without giving up type safety, provided their bounds match the direction of data flow. Start from what the method does with the values, then choose the narrowest clear signature.
Further reading
- Dev.java: wildcards
- Oracle Java Tutorial: wildcard guidelines
- Java Language Specification: type erasure
Want a structured Java learning path?
Explore Jaipur Engineers course options to connect Java fundamentals, debugging, backend development and project practice in a guided learning plan.