Skip to lesson

Wildcards: ?, ? extends, ? super

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

ArrayStoreDemo.javaJava
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");    }}
Sample output (the program stops with an exception)
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 a Number[], so Number[] numbers = tickets; compiles.
  • numbers[1] = 4.5 also compiles, because a Double is a Number. Only the JVM sees that the real array holds Integers, and it throws ArrayStoreException.

Example 2 · Generics refuse it at compile time

InvariantDemo.javaJava
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);    }}
Sample compiler output
InvariantDemo.java:7: error: incompatible types: ArrayList<Integer> cannot be converted to ArrayList<Number>
        ArrayList<Number> numbers = tickets;
                                    ^
1 error

What this code does

  • The same idea with lists stops at line 7: an ArrayList<Integer> is not an ArrayList<Number>.
  • So the Double can 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.

Java
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 compile

Inside 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

ExtendsDemo.javaJava
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));    }}
Output
Items: Rs. 8500.0
Fees: Rs. 149.0

What this code does

  • ArrayList<? extends Number> accepts ArrayList<Integer> and ArrayList<Double>: any list whose elements are some kind of Number.
  • Whatever the real type is, each element IS-A Number, so reading it as Number n is safe and doubleValue() works.

Example 4 · You cannot add through ? extends

ExtendsAddDemo.javaJava
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);    }}
Sample compiler output
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 error

What this code does

  • The list might really be an ArrayList<Double>, as it is here. Adding an Integer would break it, so the Java compiler refuses every add.
  • CAP#1 is the Java compiler's name for "the unknown type behind this ?". The message says it extends Number, 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

SuperDemo.javaJava
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);    }}
Output
[101, 102, 103]
[201, 202]
[Morning batch, 301]
First log entry: Morning batch

What this code does

  • ArrayList<? super Integer> accepts a list of Integer, Number or Object: any list that can hold an Integer.
  • So target.add(t) is always safe. Printing a list with println shows its elements in square brackets.
  • Reading back gives only Object: the list might hold other things, as log holds 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.

import java.util.ArrayList;
public class FeeFix {
static void addFee(ArrayList<? extends Number> amounts) {
amounts.add(50);
}
}

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.

A small class tree: Object at the top, Number below it, Integer and Double below Number. ? extends Number covers Number, Integer and Double: you can read a Number from it. ? super Integer covers Integer, Number and Object: you can add an Integer to it.

Example 6 · Copy from one list into another

CopyDemo.javaJava
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);    }}
Output
Month report: [12000, 9500, 99.5]
Audit log: [12000, 9500]

What this code does

  • from is only read, so it is ? extends T; to is only added to, so it is ? super T.
  • In copy(todaysBills, monthReport) the Java compiler infers T = Integer: an ArrayList<Integer> gives Integers, and an ArrayList<Number> can hold them.
  • With plain ArrayList<T> for both, that call would not compile: T cannot be Integer and Number at 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