Java Wildcards
The Problem Wildcards Solve
Generic types are invariant: even though Integer is a subtype of Number, List<Integer> is not a subtype of List<Number> (Generic Types lesson). That rule prevents bugs, but it also makes some perfectly reasonable methods too restrictive:
static double sumStrict(List<Number> values) { ... }
List<Integer> ints = new ArrayList<>();
sumStrict(ints); // compile error: List<Integer> cannot be converted to List<Number>
A method that only reads numbers from a list should accept a list of integers, a list of doubles, or a list of any other kind of number. Wildcards express exactly that. A wildcard is a ? used as a type argument, meaning "some type, not known exactly":
| Wildcard | Read as | Accepts |
|---|---|---|
List<?> | a list of some unknown type | List<String>, List<Integer>, any list |
List<? extends Number> | a list of some type that is a Number | List<Number>, List<Integer>, List<Double>, ... |
List<? super Integer> | a list of some type that is a supertype of Integer | List<Integer>, List<Number>, List<Object> |
Wildcards appear in variable and parameter types. You never create an object with a wildcard (new ArrayList<?>() is illegal); you use them to say what a method or variable accepts.
The Three Kinds of Wildcard
import java.util.*;
public class W1 {
static double sumStrict(List<Number> values) {
double t = 0;
for (Number n : values) t += n.doubleValue();
return t;
}
static double sum(List<? extends Number> values) {
double t = 0;
for (Number n : values) t += n.doubleValue();
return t;
}
static void printAll(Collection<?> items) {
System.out.println(items.size() + " items: " + items);
}
static void addDefaults(List<? super Integer> target) {
target.add(10);
target.add(20);
}
public static void main(String[] args) {
List<Integer> ints = List.of(1, 2, 3);
List<Double> prices = List.of(99.5, 0.5);
System.out.println(sum(ints) + " " + sum(prices));
printAll(List.of("a", "b"));
printAll(Set.of(42));
List<Number> numbers = new ArrayList<>();
List<Object> objects = new ArrayList<>(List.of("header"));
addDefaults(numbers);
addDefaults(objects);
System.out.println(numbers + " " + objects);
}
}
Output:
6.0 100.0
2 items: [a, b]
1 items: [42]
[10, 20] [header, 10, 20]
Upper-bounded: ? extends T
sum(List<? extends Number>) accepts a List<Integer> and a List<Double>. Inside the method, every element can be read as a Number, because whatever the actual element type is, it's some subtype of Number.
Unbounded: ?
printAll(Collection<?>) accepts any collection. Elements can only be read as Object, which is enough for methods that use only Object's methods (toString, equals) or the collection's own methods (size, isEmpty, clear). Collection<?> is the type-safe replacement for the raw type Collection.
Lower-bounded: ? super T
addDefaults(List<? super Integer>) accepts a List<Integer>, a List<Number> or a List<Object>. Whatever the actual element type is, it's a supertype of Integer, so adding an Integer is always safe.
What You Can Read and Write
Each wildcard trades away one ability for flexibility. The compiler enforces this:
import java.util.*;
public class E1 {
static double sumStrict(List<Number> values) { return 0; }
static void broken(List<? extends Number> values, List<? super Integer> sink) {
values.add(3);
Integer first = sink.get(0);
}
public static void main(String[] args) {
sumStrict(List.of(1, 2, 3));
List<Integer> ints = new ArrayList<>();
sumStrict(ints);
}
}
E1.java:7: error: incompatible types: int cannot be converted to CAP#1
values.add(3);
^
where CAP#1 is a fresh type-variable:
CAP#1 extends Number from capture of ? extends Number
E1.java:8: error: incompatible types: CAP#1 cannot be converted to Integer
Integer first = sink.get(0);
^
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: Integer from capture of ? super Integer
E1.java:14: error: incompatible types: List<Integer> cannot be converted to List<Number>
sumStrict(ints);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors
- You can't add to a
List<? extends Number>(exceptnull). The list might really be aList<Double>; adding theInteger3 would corrupt it. The compiler represents the unknown element type asCAP#1(a captured type variable) and can't prove that3is aCAP#1. - Reading from a
List<? super Integer>gives onlyObject. The list might be aList<Object>containing strings, so its elements can't be assumed to beInteger. - Note that line 12,
sumStrict(List.of(1, 2, 3)), compiled:List.ofis generic, and the compiler inferredList<Number>from the parameter type. Only an existingList<Integer>variable (line 14) is rejected.
Reading in practice:
import java.util.*;
public class Read {
public static void main(String[] args) {
List<? extends Number> producer = List.of(1, 2.5, 3L);
Number n = producer.get(1);
System.out.println("read from ? extends: " + n);
List<? super Integer> consumer = new ArrayList<Number>(List.of(7.5));
consumer.add(5);
Object o = consumer.get(0);
System.out.println("read from ? super: " + o + " (" + o.getClass().getSimpleName() + "), list " + consumer);
}
}
Output:
read from ? extends: 2.5
read from ? super: 7.5 (Double), list [7.5, 5]
| Read elements as | Add elements | |
|---|---|---|
List<T> | T | T |
List<? extends T> | T | Nothing (only null) |
List<? super T> | Object | T (and its subtypes) |
List<?> | Object | Nothing (only null) |
The consumer list really is a List<Number> containing a Double; the code could add an Integer to it, but reading gave back an Object — the only type that's safe for every possible supertype of Integer.
PECS: Producer Extends, Consumer Super
A memorable rule (from Effective Java) decides which wildcard to use for a parameter:
- If the parameter produces values your method reads → use
? extends T. - If the parameter consumes values your method writes → use
? super T. - If it does both → use plain
T, no wildcard.
import java.util.*;
import java.util.function.*;
public class Pecs {
static <T> void copy(List<? extends T> source, List<? super T> target) {
for (T item : source) target.add(item);
}
static <T> List<T> filter(Collection<? extends T> items, Predicate<? super T> keep) {
List<T> out = new ArrayList<>();
for (T item : items) if (keep.test(item)) out.add(item);
return out;
}
public static void main(String[] args) {
List<Integer> marks = List.of(91, 45, 78);
List<Double> fees = List.of(4999.0, 2999.0);
List<Number> all = new ArrayList<>();
copy(marks, all);
copy(fees, all);
System.out.println("all numbers: " + all);
Predicate<Number> positive = n -> n.doubleValue() > 50;
Predicate<Object> notNull = Objects::nonNull;
List<Integer> passed = filter(marks, positive);
List<Integer> present = filter(marks, notNull);
System.out.println("passed: " + passed + ", present: " + present.size());
List<Integer> sorted = new ArrayList<>(marks);
Comparator<Number> byDouble = Comparator.comparingDouble(Number::doubleValue);
sorted.sort(byDouble);
System.out.println("sorted with Comparator<Number>: " + sorted);
}
}
Output:
all numbers: [91, 45, 78, 4999.0, 2999.0]
passed: [91, 78], present: 3
sorted with Comparator<Number>: [45, 78, 91]
copy: the source produces items (? extends T), the target consumes them (? super T). Integers and doubles can both be copied into aList<Number>. Without wildcards,copywould require all three lists to have exactly the same element type. The JDK'sCollections.copy(List<? super T> dest, List<? extends T> src)is declared this way.filter: the items are produced (? extends T); the predicate consumes each item to test it (? super T). So aList<Integer>can be filtered with aPredicate<Number>or even aPredicate<Object>— a general predicate works for more specific elements.List.sort(Comparator<? super E>): aComparator<Number>consumes numbers, so it can sort aList<Integer>. This is the same idea that madeComparable<? super T>necessary forLocalDatein the Bounded Types lesson.
Functional interfaces follow the rule naturally: a Function<T, R> parameter is usually declared Function<? super T, ? extends R> — it consumes Ts and produces Rs. That's why the JDK's signatures, such as Stream.map(Function<? super T, ? extends R> mapper), look the way they do.
Wildcard Capture and Helper Methods
Because the element type of a List<?> is unknown, the compiler won't even let you put back an element you just took out of the same list:
import java.util.*;
public class CapErr {
static void swapFirstLast(List<?> list) {
Object first = list.get(0);
list.set(0, list.get(list.size() - 1));
}
}
CapErr.java:6: error: incompatible types: Object cannot be converted to CAP#1
list.set(0, list.get(list.size() - 1));
^
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
The standard fix is a private generic helper method that "captures" the wildcard as a named type parameter:
import java.util.*;
public class Capture {
static void swapFirstLast(List<?> list) {
swapHelper(list);
}
private static <T> void swapHelper(List<T> list) {
T first = list.get(0);
list.set(0, list.get(list.size() - 1));
list.set(list.size() - 1, first);
}
public static void main(String[] args) {
List<String> cities = new ArrayList<>(List.of("Chennai", "Madurai", "Salem"));
swapFirstLast(cities);
System.out.println(cities);
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4));
swapFirstLast(nums);
System.out.println(nums);
}
}
Output:
[Salem, Madurai, Chennai]
[4, 2, 3, 1]
When swapHelper(list) is called, the compiler infers T as the captured unknown type. Inside the helper, the elements have a name (T), so reading and writing them is allowed. The public method keeps the simple List<?> signature; the JDK's Collections.swap(List<?> list, int i, int j) and Collections.reverse(List<?>) use this technique.
Wildcard or Type Parameter?
Both of these accept a list of any numbers:
static double sum(List<? extends Number> values)
static <T extends Number> double sum(List<T> values)
Guidelines:
- Use a wildcard when the type is used only once in the signature and you don't need to name it — it's simpler to read.
- Use a type parameter when the same type must appear in several places to relate them — for example,
static <T> T lastOf(List<T> list)links the return type to the element type, andstatic <T> void copy(List<? extends T> src, List<? super T> dst)links two parameters. - Avoid wildcards in return types. A method returning
List<? extends Number>forces every caller to deal with the wildcard's restrictions. Return a concrete type such asList<Number>orList<T>instead.
Practical Example: A Type-Safe Event Bus
Applications often publish events — an order was placed, a user signed up — to which other parts of the system subscribe: send an invoice, send a welcome email, write an audit log. A small event bus shows several wildcard rules working together, including handlers that are more general than the event they handle.
import java.time.Instant;
import java.util.*;
import java.util.function.Consumer;
public class Events {
interface Event { Instant at(); }
record OrderPlaced(String orderId, double amount, Instant at) implements Event { }
record UserSignedUp(String email, Instant at) implements Event { }
static class EventBus {
private final Map<Class<?>, List<Consumer<? super Event>>> handlers = new LinkedHashMap<>();
<E extends Event> void subscribe(Class<E> type, Consumer<? super E> handler) {
handlers.computeIfAbsent(type, t -> new ArrayList<>())
.add(event -> handler.accept(type.cast(event)));
}
void publish(Event event) {
for (Map.Entry<Class<?>, List<Consumer<? super Event>>> entry : handlers.entrySet()) {
if (entry.getKey().isInstance(event)) {
entry.getValue().forEach(h -> h.accept(event));
}
}
}
void publishAll(Collection<? extends Event> events) {
for (Event e : events) publish(e);
}
}
public static void main(String[] args) {
EventBus bus = new EventBus();
List<String> audit = new ArrayList<>();
Consumer<Event> auditor = e -> audit.add(e.getClass().getSimpleName() + "@" + e.at());
Consumer<Object> printer = o -> System.out.println(" got " + o);
bus.subscribe(OrderPlaced.class, o -> System.out.println(" invoice for " + o.orderId() + ": Rs " + o.amount()));
bus.subscribe(UserSignedUp.class, u -> System.out.println(" welcome mail to " + u.email()));
bus.subscribe(Event.class, auditor);
bus.subscribe(UserSignedUp.class, printer);
Instant t = Instant.parse("2026-11-15T10:00:00Z");
List<OrderPlaced> orders = List.of(new OrderPlaced("O-1", 2500, t), new OrderPlaced("O-2", 800, t.plusSeconds(5)));
bus.publishAll(orders);
bus.publish(new UserSignedUp("asha@gocourse.in", t.plusSeconds(9)));
System.out.println("audit: " + audit);
}
}
Output:
invoice for O-1: Rs 2500.0
invoice for O-2: Rs 800.0
welcome mail to asha@gocourse.in
got UserSignedUp[email=asha@gocourse.in, at=2026-11-15T10:00:09Z]
audit: [OrderPlaced@2026-11-15T10:00:00Z, OrderPlaced@2026-11-15T10:00:05Z, UserSignedUp@2026-11-15T10:00:09Z]
Where the wildcards matter:
subscribe(Class<E> type, Consumer<? super E> handler)— a handler consumes events, so? super Elets a general handler subscribe to a specific event type.printer, aConsumer<Object>, subscribes toUserSignedUp;auditor, aConsumer<Event>, subscribes to all events. WithConsumer<E>, both would be rejected.- Lambdas get the precise type. For
subscribe(OrderPlaced.class, o -> ...), the compiler infersE = OrderPlaced, soo.orderId()ando.amount()are available inside the lambda without casts. Class<E>as a runtime type token. Because generic types are erased at runtime (next lesson), the bus can't otherwise know which events a handler wants. TheClassobject is stored as the map key;isInstancechecks whether an event matches (so subscribing toEvent.classmatches every event), andtype.cast(event)performs a checked cast before calling the typed handler.publishAll(Collection<? extends Event>)— the collection produces events, so aList<OrderPlaced>is accepted. WithCollection<Event>, the caller would have to copy it into a new list first.- Storage uses
Consumer<? super Event>. Each stored handler is a small adapter lambda that accepts anyEvent, casts it and forwards it, so handlers for different event types can live in one map safely.
Frameworks such as Spring's application events and Guava's EventBus use these same techniques — class tokens for dispatch and ? super for handler flexibility.