Introduction
Java Generics shipped in September 2004 as part of Java 5 (JSR-14 by Gilad Bracha, Peter Ahe, Neal Gafter, and the JSR-14 expert group). The wildcard mechanism (? extends T, ? super T, and the unbounded ?) was designed to handle the variance problem: if List<Integer> were declared a subtype of List<Number>, the type system would be unsound because you could add a Double to what you think is a List<Integer>. The PECS rule (Producer Extends, Consumer Super) was coined by Joshua Bloch in Effective Java (first edition 2001, second edition 2008, third edition 2018) and is the practical mnemonic for choosing between the two bounded wildcard forms. For a Java learner, Java Generics wildcards and the PECS rule are the modern way to write flexible, type-safe APIs. Interviewers ask about wildcards because they are the clearest test of whether a candidate understands variance, type erasure, and the difference between in and out parameters.
Understanding Java Generics wildcards also clarifies why the Java Collections framework signatures look the way they do. The Collections.copy signature <T> void copy(List<? super T> dest, List<? extends T> src), the Collections.max signature <T> T max(Collection<? extends T> coll, Comparator<? super T> comp), and the List.replaceAll signature void replaceAll(UnaryOperator<E> operator) all use wildcards and PECS to maximise call-site flexibility without sacrificing type safety. Every well-designed generic API follows the same rules.
What are Java Generics Wildcards?
Java Generics wildcards are a special type-argument syntax that lets a generic type accept a family of types instead of one specific type. The ? extends T form is an upper-bounded wildcard: the type argument is T or any subtype. The ? super T form is a lower-bounded wildcard: the type argument is T or any supertype. The unbounded ? form means "any type". The PECS rule is the mnemonic: if the variable is a producer (you read T out of it), use ? extends T; if the variable is a consumer (you write T into it), use ? super T. Java Generics wildcards belong to the type system category, not the runtime category. They are different from generic type parameters in that they do not bind a name to the type; they only specify a constraint at a single use site. They are different from raw types (List without type parameter) in that wildcards preserve type safety at compile time, while raw types disable the type checker entirely.
Wildcards are use-site variance, as opposed to the declaration-site variance that Scala and Kotlin use (where List is covariant in its type parameter by declaration, not by use-site wildcard). Use-site variance is more flexible at the call site but more verbose at the declaration; declaration-site variance is cleaner at the use site but constrains the declaration. The Java design choice is the older one and matches the Java philosophy of explicitness at every use site.
How Java Generics Wildcards Work - Step by Step
Step 1: Upper-bounded wildcards (? extends T). A List<? extends Number> can hold a List<Integer>, List<Double>, or List<Number>. From this list, you can read a Number (every element is at least a Number, so the compiler types the result of get as Number), but you cannot add any element except null (because the actual type might be List<Integer> and you would be adding a Double). The upper bound makes the type covariant: it widens the set of acceptable arguments.
Step 2: Lower-bounded wildcards (? super T). A List<? super Integer> can hold a List<Number>, List<Object>, or List<Integer>. From this list, you can add an Integer (every element is at most Number, so an Integer fits), but you cannot read anything more specific than Object (because the actual type might be List<Object> and what you read could be a String). The lower bound makes the type contravariant: it widens the set of acceptable arguments in the opposite direction.
Step 3: The PECS rule. If a parameter is a producer (you read T out of it), use ? extends T. If a parameter is a consumer (you write T into it), use ? super T. If it is both, use neither (use T directly so that the same T is shared between the producer and consumer sides). If it is neither, use ? (unbounded, accepts anything but you can only read Object and write null). The Collections.copy(List<? super T> dest, List<? extends T> src) signature is the canonical example: src is a producer of T, dest is a consumer of T.
Step 4: Capture of wildcards. Internally, javac treats each wildcard as a fresh captured type variable (capture#1 of ? extends T). The capture is what lets the compiler know that two reads from the same List<? extends T> are guaranteed to be the same captured type, even though we do not know what type it is. Capture is the magic that makes wildcards sound: without it, you could not prove that two reads from the same wildcard list are compatible.
Step 5: Bounded type variables versus wildcards. <T extends Number> is a bounded type variable, not a wildcard. The difference is that T is a name you can refer to throughout the method (in the return type, in multiple parameters, in the body); a wildcard is anonymous and scoped to a single use site. Use bounded type variables when you need to refer to the type more than once; use wildcards when you only need to express variance at a single use site.
Step 6: Multiple bounds and intersection. <T extends Comparable<T> & Serializable> is a multi-bound type variable; the equivalent wildcard form (? extends Comparable<?> & Serializable) does not exist in Java. Use a type variable when you need intersection bounds. The Collections.sort signature <T extends Comparable<? super T>> void sort(List<T> list) is a famous use of nested bounds: T must be comparable to itself or any supertype, which lets you sort List<LocalDate> using a Comparator<ChronoLocalDate>.
Java Program for Java Generics Wildcards (PECS Rule)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PecsDemo {
// PECS in action: src is a producer (? extends T),
// dest is a consumer (? super T).
public static <T> void copy(List<? super T> dest,
List<? extends T> src) {
for (T t : src) {
dest.add(t);
}
}
public static void main(String[] args) {
// 1. copy from List<Integer> into List<Number>
List<Integer> src = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Number> dest = new ArrayList<>();
copy(dest, src);
System.out.println("dest after copy: " + dest);
// 2. Upper-bounded wildcard: read Number from List<? extends Number>
List<? extends Number> numbers = src;
Number first = numbers.get(0);
System.out.println("first read as Number: " + first);
// 3. Lower-bounded wildcard: write Integer into List<? super Integer>
List<? super Integer> sink = new ArrayList<Number>();
sink.add(Integer.valueOf(99));
System.out.println("sink size after write: " + sink.size());
// 4. Unbounded wildcard: accepts List<anything>
List<?> anything = src;
Object obj = anything.get(0);
System.out.println("unbounded read gives Object: " + obj);
}
}
Code Explanation - Line by Line
The copy method is the canonical PECS example. It declares a type variable T that is shared between src (a List<? extends T> producer) and dest (a List<? super T> consumer). The body iterates src with a for-each loop that yields T (the captured type), and adds each T to dest. The compiler proves type safety because the captured type from src is the same T that dest accepts as a write; if you swapped the wildcards (List<? extends T> dest, List<? super T> src) the code would not compile because you would be trying to write to a producer and read from a consumer.
The first call in main demonstrates the practical benefit of PECS: it lets you copy from List<Integer> into List<Number>. Without wildcards (signature <T> void copy(List<T> dest, List<T> src)) the call would not compile because List<Integer> and List<Number> are different types due to generics invariance. With PECS the call site is fine: src accepts List<Integer> because Integer is a subtype of Number, dest accepts List<Number> because Number is a supertype of Integer.
The second block in main demonstrates reading from a List<? extends Number>. The variable numbers is typed as List<? extends Number> so it can hold a List<Integer>, List<Double>, or List<Number>. The result of numbers.get(0) is typed as Number by the compiler; you cannot cast it to Integer because the actual list might be List<Double>.
The third block demonstrates writing to a List<? super Integer>. The variable sink is typed as List<? super Integer> so it can hold a List<Integer>, List<Number>, or List<Object>. Calling sink.add(Integer.valueOf(99)) is type-safe because every element of the actual list is at least a Number (or an Object), and Integer is a Number, so the add succeeds. Reading from sink would give Object, not Integer, because the actual list might be List<Object>.
The fourth block demonstrates the unbounded List<?>. The variable anything can hold a List of any type; you can read Object (everything is an Object) but you cannot write anything but null. The unbounded wildcard is useful for utility methods that do not care about the element type, like the List.size or List.clear methods.
Interview Questions and Answers
Q1. What does PECS stand for and where does it come from?
PECS stands for "Producer Extends, Consumer Super". It was coined by Joshua Bloch in Effective Java as the mnemonic for choosing between upper-bounded and lower-bounded wildcards. If a parameter is a producer of T (you read T from it), declare it as List<? extends T>. If it is a consumer of T (you write T into it), declare it as List<? super T>. The rule is the practical application of variance theory to the Java type system, and it is the standard pattern for every generic API in the JDK.
Q2. Why can you not add an element to a List<? extends Number>?
Because the actual type might be List<Integer>, List<Double>, or List<Number>, and the compiler cannot prove that the element you are adding is of the correct runtime type. The only safe value to add is null, because null is assignable to any reference type. The compiler therefore rejects list.add(Integer.valueOf(1)) even though Integer is a Number, because the actual list might be a List<Double> and adding an Integer to a List<Double> would be unsound.
Q3. Why can you not read anything more specific than Object from a List<? super Integer>?
Because the actual type might be List<Object>, List<Number>, or List<Integer>, and reading the element back you can only be sure it is at least an Object. The compiler therefore types the result of list.get(0) as Object, not Integer. To read an Integer specifically, you would need a List<Integer> or a List<? extends Integer>. The lower bound widens the set of acceptable list types but narrows the set of operations you can do (writes yes, typed reads no).
Q4. When would you use a bounded type variable instead of a wildcard?
Use a bounded type variable (T extends Number) when you need to refer to the type by name in multiple places: the return type, multiple parameters, or inside the method body. Use a wildcard (? extends Number) when you only need to express variance at a single use site (one parameter, no return type dependency). The classic signature <T extends Comparable<? super T>> void sort(List<T> list) uses a type variable because T appears multiple times and constrains itself recursively; a wildcard cannot express that.
Q5. What is the difference between List<?> and List<Object>?
List<?> is the unbounded wildcard: it accepts List<String>, List<Integer>, List of anything. You can read Object from it (everything is an Object) but you cannot add anything but null. List<Object> is a concrete parameterised type: it only accepts List<Object> (because generics are invariant). You can add any Object to a List<Object>. The two are very different in type-system terms even though they look similar; List<Object> is rarely what you want, and List<?> is almost always the safer choice for a polymorphic utility.
Q6. How does wildcard capture work and why does it matter?
Wildcard capture is the compiler's mechanism for treating each occurrence of a wildcard as a fresh, anonymous type variable. When you pass a List<?> to a method that takes List<T>, the compiler captures the wildcard into a fresh type variable capture#1 of ? and binds T to it. Capture lets the compiler prove type safety across multiple reads from the same wildcard list: it knows that two reads return the same captured type even though it does not know what type that is. Without capture, you could not implement methods like swap that need to refer to the type between reads and writes.
Q7. Your team is writing a generic utility method public static <T> void copy(List<T> dest, List<T> src) and the API feels too restrictive. How would you apply the PECS rule to make it more flexible without breaking type safety?
Change the signature to public static <T> void copy(List<? super T> dest, List<? extends T> src). The source src is a T producer, so it should be List<? extends T> to accept List<Integer> when T is Number. The destination dest is a T consumer, so it should be List<? super T> to accept List<Object> when T is Number. This signature is exactly the one java.util.Collections.copy uses. It widens the acceptable inputs without sacrificing compile-time type safety; the only change is that the method cannot read T from dest (it can only write), which is fine for a copy utility that only writes.
Sample Input and Output
Input: src = [1, 2, 3] as List<Integer>
dest = [] as List<Number>
numbers = src view as List<? extends Number>
sink = new ArrayList<Number>() view as List<? super Integer>
anything = src view as List<?>
Output:
dest after copy: [1, 2, 3]
first read as Number: 1
sink size after write: 1
unbounded read gives Object: 1
The output confirms four behaviours: the copy call accepted List<Number> as dest and List<Integer> as src because of the PECS wildcards, and copied all three Integer elements into the Number list; the upper-bounded wildcard let us read a Number from the List<? extends Number> view of src; the lower-bounded wildcard let us write an Integer into the List<? super Integer> sink; and the unbounded List<?> let us read an Object from the same src list without any constraint on the element type.
Common Mistakes to Avoid
First, using List<Object> when you mean List<?>. List<Object> is invariant and rejects List<String>; List<?> is unbounded and accepts anything. The two are not interchangeable, and using List<Object> for a polymorphic utility forces the caller to copy the data into a new List<Object> first.
Second, ignoring the PECS rule and using raw T everywhere. This produces signatures that compile but are inflexible at call sites. The Collections framework signatures were revised in Java 5 to use wildcards precisely to avoid this inflexibility; every public generic API should follow the same pattern.
Third, trying to add to a List<? extends T>. The compiler rejects this with a confusing "cannot find symbol" error because the captured type does not have an add method that accepts your concrete type. The fix is to use List<T> or List<? super T> for any parameter you intend to write to.
Fourth, attempting to write a List<? extends T> element back into a List<? extends T>. Even read-then-write on the same wildcard list fails because the two captures are unrelated to the compiler; the read gives capture#1 and the write expects capture#2, and the compiler cannot prove they are the same type. Use a generic helper method <U extends T> void swap(List<U> list, int i, int j) that captures the wildcard into a single U to express this pattern.
Real-World Applications
Java Generics wildcards are everywhere in the JDK. The Collections framework signatures all use PECS: Collections.addAll(Collection<? super T>, T...), Collections.copy(List<? super T> dest, List<? extends T> src), Collections.max(Collection<? extends T> coll, Comparator<? super T> comp), and Collections.sort(List<T> list, Comparator<? super T> c). The Class<T> class uses Class<? extends T> for Class.cast and Class<? super T> for getEnumConstants. The Stream API uses wildcards for peek, map, and collect signatures to maximise call-site flexibility.
In the library ecosystem, Guava's ImmutableList.copyOf(Collection<? extends E> elements), RxJava's Observable<? extends T>, and Project Reactor's Flux<? extends T> all use wildcards. Spring's ApplicationContext.getBeansOfType(Class<? extends T> type) uses an upper-bounded wildcard so you can ask for all beans implementing some interface. Hibernate's CriteriaQuery<T> setProjection(...? extends T) uses wildcards extensively. Every well-designed generic library follows the PECS rule at every public API boundary because it is the only way to be both type-safe and flexible at the call site.
Conclusion
Java Generics wildcards and the PECS rule are the modern way to write flexible, type-safe generic APIs. The two wildcard forms (? extends T for producers, ? super T for consumers) and the unbounded ? form cover the three practical variance cases. We walked through upper-bounded reads, lower-bounded writes, the unbounded wildcard, the capture mechanism that makes wildcards sound, and the trade-off between wildcards and bounded type variables. To go deeper, study Joshua Bloch's Effective Java item on bounded wildcards, then read the Java Language Specification section on capture conversion. After that, the natural next topics are Java Generics type erasure and the bridge-method synthesis that erasure forces.
Comments
Comments
Post a Comment