Wildcards: ?, ? extends, ? super
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A wildcard is a ? used as a type argument, like ArrayList<?>, ArrayList<? extends Number> or ArrayList<? super Integer>. It lets one method accept a whole family of generic types, while the Java compiler (javac) still blocks every unsafe read or write. The examples use ArrayList, Java's growing list, with only add, get, size and a for-each loop; ArrayList basics (opens in a new tab) covers it fully.
ArrayList<Integer> is not an ArrayList<Number>
Invariance means a generic type does not follow its type argument's family tree: ArrayList<Integer> is not an ArrayList<Number>, even though Integer is a Number. Two generic types match only when their type arguments are exactly the same.
An Integer is a Number, so you might expect a list of tickets to pass as a list of numbers. Arrays do allow that, and they pay for it at run time.
Example 1 · Arrays allow it, then crash
public class ArrayStoreDemo { public static void main(String[] args) { Integer[] tickets = { 101, 102, 103 }; Number[] numbers = tickets; System.out.println("First: " + numbers[0]); numbers[1] = 4.5; System.out.println("Stored 4.5"); }}First: 101 Exception in thread "main" java.lang.ArrayStoreException: java.lang.Double at ArrayStoreDemo.main(ArrayStoreDemo.java:6)
What this code does
- Arrays allow this: an
Integer[]counts as aNumber[], soNumber[] numbers = tickets;compiles. numbers[1] = 4.5also compiles, because aDoubleis aNumber. Only the JVM sees that the real array holdsIntegers, and it throwsArrayStoreException.
Example 2 · Generics refuse it at compile time
import java.util.ArrayList;
public class InvariantDemo { public static void main(String[] args) { ArrayList<Integer> tickets = new ArrayList<>(); tickets.add(101); ArrayList<Number> numbers = tickets; numbers.add(4.5); }}InvariantDemo.java:7: error: incompatible types: ArrayList<Integer> cannot be converted to ArrayList<Number>
ArrayList<Number> numbers = tickets;
^
1 errorWhat this code does
- The same idea with lists stops at line 7: an
ArrayList<Integer>is not anArrayList<Number>. - So the
Doublecan never get into the list of tickets. The safety costs flexibility, which wildcards give back.
If the Java compiler allowed numbers = tickets, then numbers.add(4.5) would put a Double into a list of Integers, and the crash would come much later, somewhere else. Generics refuse at once; wildcards, below, give back the flexibility safely.
The unbounded wildcard ?
A wildcard is a ? used as a type argument, meaning "some type, I do not know which". ArrayList<?> accepts a list of any element type; you can read its elements as Object, but you cannot add to it, except null.
A method that only prints a list does not care about the element type. ArrayList<Object> will not do, because of invariance. Write ArrayList<?>: a list of some type.
static void printAll(ArrayList<?> items) { for (Object item : items) { System.out.print(item + " "); } System.out.println("(" + items.size() + " items)");}// printAll(tickets) and printAll(products) both compileInside printAll, each element is known only as an Object, which is enough to print it. items.add("Keyboard") does not compile: the list might be an ArrayList<Integer>, and the Java compiler cannot prove a String fits. ArrayList<?> is the safe version of the raw ArrayList.
? extends: safe to read
An upper-bounded wildcard, ? extends T, accepts a generic type whose type argument is T or any subtype of T. You can safely read its elements as T, but you cannot add to it, because the real element type is unknown.
A bill total only reads numbers, so it should take a list of Integer prices or of Double fees. Write ArrayList<? extends Number>: a list of some kind of Number.
Example 3 · Read with ? extends Number
import java.util.ArrayList;
public class ExtendsDemo { static double total(ArrayList<? extends Number> amounts) { double sum = 0; for (Number n : amounts) { sum += n.doubleValue(); } return sum; }
public static void main(String[] args) { ArrayList<Integer> prices = new ArrayList<>(); prices.add(6000); prices.add(2000); prices.add(500);
ArrayList<Double> fees = new ArrayList<>(); fees.add(99.5); fees.add(49.5);
System.out.println("Items: Rs. " + total(prices)); System.out.println("Fees: Rs. " + total(fees)); }}Items: Rs. 8500.0 Fees: Rs. 149.0
What this code does
ArrayList<? extends Number>acceptsArrayList<Integer>andArrayList<Double>: any list whose elements are some kind ofNumber.- Whatever the real type is, each element IS-A
Number, so reading it asNumber nis safe anddoubleValue()works.
Example 4 · You cannot add through ? extends
import java.util.ArrayList;
public class ExtendsAddDemo { static void addFee(ArrayList<? extends Number> amounts) { amounts.add(50); }
public static void main(String[] args) { ArrayList<Double> fees = new ArrayList<>(); addFee(fees); }}ExtendsAddDemo.java:5: error: incompatible types: int cannot be converted to CAP#1
amounts.add(50);
^
where CAP#1 is a fresh type-variable:
CAP#1 extends Number from capture of ? extends Number
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorWhat this code does
- The list might really be an
ArrayList<Double>, as it is here. Adding anIntegerwould break it, so the Java compiler refuses every add. CAP#1is the Java compiler's name for "the unknown type behind this?". The message says it extendsNumber, and nothing more.
Compare it with the bounded method of Bounded types (opens in a new tab), <T extends Number> double total(T[] a). Both read numbers; the wildcard needs no name because nothing else in the header refers to the type.
? super: safe to add
A lower-bounded wildcard, ? super T, accepts a generic type whose type argument is T or any supertype of T. You can safely add T values to it, but reading gives only Object, because the list may hold other things too.
The ticket machine adds new ticket numbers to a list. Any list that can hold an Integer will do: an ArrayList<Integer>, ArrayList<Number> or ArrayList<Object>. Write ArrayList<? super Integer>.
Example 5 · Write with ? super Integer
import java.util.ArrayList;
public class SuperDemo { static void addTickets(ArrayList<? super Integer> target, int from, int to) { for (int t = from; t <= to; t++) { target.add(t); } }
public static void main(String[] args) { ArrayList<Integer> tickets = new ArrayList<>(); ArrayList<Number> numbers = new ArrayList<>(); ArrayList<Object> log = new ArrayList<>(); log.add("Morning batch");
addTickets(tickets, 101, 103); addTickets(numbers, 201, 202); addTickets(log, 301, 301);
System.out.println(tickets); System.out.println(numbers); System.out.println(log); Object first = log.get(0); System.out.println("First log entry: " + first); }}[101, 102, 103] [201, 202] [Morning batch, 301] First log entry: Morning batch
What this code does
ArrayList<? super Integer>accepts a list ofInteger,NumberorObject: any list that can hold anInteger.- So
target.add(t)is always safe. Printing a list withprintlnshows its elements in square brackets. - Reading back gives only
Object: the list might hold other things, aslogholds the text "Morning batch".
Fix the error
extends or super?
Read the real compiler error, then pick the header that fixes it.
Round 1 of 3
addFee should add a Rs. 50 delivery fee to any list that can hold Integers.
Error
FeeFix.java:5: error: incompatible types: int cannot be converted to CAP#1
amounts.add(50);
^Read from one list, add into another
A method that reads from one list and adds into another needs both wildcards: ? extends T for the list it reads from, ? super T for the list it adds into. If one list is both read and changed, use plain T.
Example 6 · Copy from one list into another
import java.util.ArrayList;
public class CopyDemo { static <T> void copy(ArrayList<? extends T> from, ArrayList<? super T> to) { for (T item : from) { to.add(item); } }
public static void main(String[] args) { ArrayList<Integer> todaysBills = new ArrayList<>(); todaysBills.add(12000); todaysBills.add(9500);
ArrayList<Double> todaysFees = new ArrayList<>(); todaysFees.add(99.5);
ArrayList<Number> monthReport = new ArrayList<>(); copy(todaysBills, monthReport); copy(todaysFees, monthReport); System.out.println("Month report: " + monthReport);
ArrayList<Object> auditLog = new ArrayList<>(); copy(todaysBills, auditLog); System.out.println("Audit log: " + auditLog); }}Month report: [12000, 9500, 99.5] Audit log: [12000, 9500]
What this code does
fromis only read, so it is? extends T;tois only added to, so it is? super T.- In
copy(todaysBills, monthReport)the Java compiler infersT = Integer: anArrayList<Integer>gives Integers, and anArrayList<Number>can hold them. - With plain
ArrayList<T>for both, that call would not compile:Tcannot beIntegerandNumberat once.
Java's own Collections.copy has this exact shape: static <T> void copy(List<? super T> dest, List<? extends T> src). Do not put wildcards in return types, though: a caller who gets an ArrayList<?> back can do almost nothing with it.
Next step
Check your understanding
12 quick questions