Java
Programming
Generics
Java Syntax
Advanced Java Concepts

Difference between <? super T> and <? extends T> in Java generics

Codemia Knowledge Hub ·

<? extends T> is an upper-bounded wildcard: the type is T or a subclass of T, which makes it safe to read elements as T. <? super T> is a lower-bounded wildcard: the type is T or a superclass of T, which makes it safe to add T values. Use extends when a method reads from a collection and super when it writes to one.

<? super T>: lower bound for writing

<? super T> requires the type to be T or a superclass of T. It suits methods that write or insert data into a collection. Think of it as "capable of holding at least T."

Example

Suppose a method should accept a list of Integer or any superclass of Integer (like Number or Object). <? super Integer> guarantees the list can hold an Integer:

java
1public static void addIntegers(List<? super Integer> list) {
2    for (int i = 0; i < 10; i++) {
3        list.add(i);
4    }
5}

Here List<? super Integer> can be List<Integer>, List<Number> or List<Object>.

<? extends T>: upper bound for reading

<? extends T> requires the type to be T or a subclass of T. It suits methods that read from a collection, because every element you read is guaranteed to be a T.

Example

To process elements from a list of Number or any subtype (like Integer or Double):

java
1public static void printNumbers(List<? extends Number> list) {
2    for (Number number : list) {
3        System.out.println(number);
4    }
5}

Here List<? extends Number> could be a List<Number>, List<Integer>, List<Double> and so on.

Side-by-side comparison

Aspect<? super T><? extends T>
DescriptionLower-bounded wildcard; T or superclass.Upper-bounded wildcard; T or subclass.
Primary UsageSafe to insert T and its subclasses.Safe to read T and treat as T.
Example Types for T = IntegerList<Integer>, List<Number>, List<Object>List<Integer> only (with T = Number, List<Double> etc. also match)
Suitable OperationsWriting to lists, stacks, and more.Reading from lists, processing elements, etc.

Choosing between them

The choice depends on whether a method needs read access (<? extends T>) or write access (<? super T>). <? extends T> treats every element as type T, so fetching elements is safe. <? super T> is more flexible about what can be added, but it does not guarantee the type of elements you retrieve unless you cast explicitly, which may lead to ClassCastException.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD