ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. Wildcards
Book 1 · Volume II — Generics, Collections & Type System · Topic 2.2

Wildcards

Unbounded, upper-bounded and lower-bounded wildcards

11 min readStage 1 · Foundations14 interview questions
Prerequisites
2.1 Bounded Type Parameters · B1V1 3.2 (array covariance)
Covers
Unbounded wildcard · Upper-bounded wildcard · Lower-bounded wildcard
Related
2.3 PECS · 3.2 Erasure Behavior · B1V3 (functional interface signatures)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

A wildcard ? in a type argument stands for "some specific type I do not name". List<?> is a list of some unknown type; List<? extends Number> is a list of some unknown subtype of Number; List<? super Integer> is a list of some unknown supertype of Integer. Wildcards make generic types behave covariantly or contravariantly where it is safe, and the compiler restricts what you can do with them so that it stays safe.

2Why It Exists

Parameterised types are invariant: List<Integer> is not a subtype of List<Number>. If it were, a method could add a Double to what is really a list of integers. Arrays made the opposite choice and pay for it with run-time ArrayStoreException checks (B1V1 3.2).

Why generics are invariant, and what arrays do instead
Figure 1 — Why generics are invariant, and what arrays do instead

Invariance is safe but restrictive: a method double sum(List<Number> l) cannot accept a List<Integer>. Wildcards solve this at the use site: double sum(List<? extends Number> l) accepts List<Integer>, List<Double> and List<Number>, while the compiler prevents the unsafe add.

3Core Concepts

? extends and ? super each describe a range of types
Figure 2 — ? extends and ? super each describe a range of types

Unbounded wildcard

List<?> means a list of some unknown type. You can read elements as Object and call operations that do not depend on the element type — size, isEmpty, clear, contains(Object), remove(Object) — but you cannot add anything except null, because the compiler cannot know what type is acceptable. Use it for code that genuinely does not care about the element type.

List<?> differs from both List<Object> and the raw List. List<Object> accepts only lists declared with Object and allows adding anything; the raw type turns off checking entirely. List<?> accepts any list and stays fully checked.

Upper-bounded wildcard

List<? extends Number> means a list of some subtype of Number. Any element read from it is at least a Number, so reading is safe. Writing is not: the list could be a List<Integer> or a List<Double>, so the compiler cannot accept any particular Number — only null. Upper-bounded wildcards make a type covariant for reading: the list is a producer of Numbers.

Lower-bounded wildcard

List<? super Integer> means a list of some supertype of Integer — List<Integer>, List<Number> or List<Object>. Writing an Integer is safe for all of them. Reading gives only Object, because the actual element type could be as general as Object. Lower-bounded wildcards make a type contravariant for writing: the list is a consumer of Integers.

Read and write capabilities of the three wildcard kinds
Figure 3 — Read and write capabilities of the three wildcard kinds
Subtype relations between parameterised and wildcard types
Figure 4 — Subtype relations between parameterised and wildcard types

4How It Works Internally

Wildcards exist only at compile time; they are erased like other type arguments (3.2). When the compiler meets an expression of wildcard type, it performs capture conversion: it replaces each ? with a fresh, unnamed type variable (shown in error messages as CAP#1) and type-checks against that. This is why list.add(list.get(0)) fails for List<?>: the value read has type CAP#1 as an Object, and the compiler cannot prove it matches the list's CAP#1 in a later expression. A private generic helper method can give the captured type a name and make such code legal.

Using a generic helper to capture a wildcard
Figure 5 — Using a generic helper to capture a wildcard

For list.add(list.get(0)) javac's message is literally "incompatible types: Object cannot be converted to CAP#1": the list wants an element of its captured type, and all the compiler knows about the value read is that it is an Object. Inside the helper of Figure 5 the captured type has a name, T, so the same two calls type-check.

5APIs / Features / Syntax

DeclarationAcceptsRead asCan add
List<Number>List<Number> onlyNumberNumber and subtypes
List<? extends Number>List<Number>, List<Integer>, List<Double> …Numbernull only
List<? super Integer>List<Integer>, List<Number>, List<Object>ObjectInteger and subtypes
List<?>Any List<X>Objectnull only
List (raw)Any list — uncheckedObjectAnything (unchecked warning)

6Practical Examples

Example 1 — Accepting lists of any numeric type

JAVAUpper-bounded wildcard as a producer
static double sum(List<? extends Number> values) {
    double total = 0;
    for (Number n : values) total += n.doubleValue();   // reading is safe
    // values.add(1);  // error: capture of ? extends Number
    return total;
}
sum(List.of(1, 2, 3));            // List<Integer>
sum(List.of(1.5, 2.5));           // List<Double>

Why it works. The parameter accepts a list of any Number subtype, and every element read from it is at least a Number, so doubleValue() is safe. The commented add(1) would be unsafe for a List<Double>, so the compiler rejects it with a message about the capture of ? extends Number. In the kit the two calls print 6.0 and 4.0.

Example 2 — Mini program: a reporting utility with all three wildcards

Problem. A small reporting utility must total quantities held as List<Integer> and prices held as List<BigDecimal>, append line numbers to lists of Number or Object, and describe any collection, without overloads, copies or casts.

JAVAWildcardReport.java
public class WildcardReport {
    // producer: reads Numbers from a list of any Number subtype
    static double total(Collection<? extends Number> values) {
        double sum = 0;
        for (Number n : values) sum += n.doubleValue();
        return sum;
    }
 
    // consumer: writes Integers into any list that can hold them
    static void addLineNumbers(List<? super Integer> target, int n) {
        for (int i = 1; i <= n; i++) target.add(i);
    }
 
    // type-independent: size and elements read as Object
    static String describe(Collection<?> c) {
        Object first = c.isEmpty() ? "-" : c.iterator().next();
        return c.size() + " items, first " + first;
    }
 
    public static void main(String[] args) {
        List<Integer> units = List.of(3, 5, 2);
        List<BigDecimal> prices =
                List.of(new BigDecimal("19.50"), new BigDecimal("5.25"));
        System.out.println("units:  " + total(units) + "  " + describe(units));
        System.out.println("prices: " + total(prices) + " " + describe(prices));
 
        List<Number> mixed = new ArrayList<>(List.of(0.5));
        addLineNumbers(mixed, 3);
        List<Object> log = new ArrayList<>(List.of("start"));
        addLineNumbers(log, 2);
        System.out.println("mixed:  " + mixed + "  log: " + log);
        // total(List.of("x"));                     // error: not a Number
        // addLineNumbers(new ArrayList<Double>(), 1); // error: no Integers
    }
}
OUTPUT
units:  10.0  3 items, first 3
prices: 24.75 2 items, first 19.50
mixed:  [0.5, 1, 2, 3]  log: [start, 1, 2]

Why it behaves this way. total only reads, so ? extends Number lets it take integers and BigDecimal alike; addLineNumbers only writes Integer values, so ? super Integer lets it fill a List<Number> that already holds a Double, or a List<Object> that holds a String; describe uses only size and elements read as Object, so Collection<?> accepts anything. The two commented calls are the guarantees: a String list is not a list of numbers, and a List<Double> cannot hold integers. The 24.75 is exact only because both prices are exact in binary; for money, sum BigDecimal values directly.

Example 3 — Accepting any list that can hold Integers

JAVALower-bounded wildcard as a consumer
static void fillWithRange(List<? super Integer> target, int n) {
    for (int i = 0; i < n; i++) target.add(i);  // writing Integers is safe
    Object first = target.get(0);                        // reading gives Object
}
List<Number> nums = new ArrayList<>();
List<Object> objs = new ArrayList<>();
fillWithRange(nums, 3);           // OK
fillWithRange(objs, 3);           // OK

Why it works. List<Number> and List<Object> can both hold integers, so ? super Integer accepts them, while List<Double> would be rejected. Inside the method, the only thing known about an element read back is that it is an Object. In the kit, both lists end up as [0, 1, 2].

Example 4 — Code that does not care about the element type

JAVAUnbounded wildcard and a capture helper
static void printSizes(Collection<?>... collections) {
    for (Collection<?> c : collections) System.out.println(c.size());
}

static void swap(List<?> list, int i, int j) { swapHelper(list, i, j); }
private static <T> void swapHelper(List<T> list, int i, int j) {
    T tmp = list.get(i);                  // the wildcard is captured as T
    list.set(i, list.get(j));
    list.set(j, tmp);
}

Why it works. printSizes uses only size(), which does not depend on the element type, so Collection<?> is the honest parameter type; Collection<?>... is a reifiable varargs type, so it causes no heap-pollution warning. swap keeps the simple public signature, and the private helper gives the captured type the name T so that get and set type-check (Figure 5). Collections.swap has the same public signature; internally it uses a raw type instead of a helper, which the JDK source itself notes is the alternative to capturing the wildcard.

Example 5 — Arrays check at run time, generics at compile time

Problem. Section 2 says that arrays are covariant and generics invariant. This program shows what each choice costs.

JAVACovarianceCheck.java
public class CovarianceCheck {
    public static void main(String[] args) {
        Integer[] ints = {1, 2};
        Object[] objs = ints;                 // arrays are covariant: compiles
        try {
            objs[0] = "one";                  // checked on every store
        } catch (ArrayStoreException e) {
            System.out.println("array store rejected: " + e.getMessage());
        }
 
        List<Integer> list = new ArrayList<>(List.of(1, 2));
        // List<Object> objList = list;       // error: generics are invariant
        List<? extends Object> view = list;   // a wildcard view is allowed ...
        // view.add("one");                   // ... but cannot be written to
        Object first = view.get(0);           // reading is safe
        System.out.println("list read: " + first + ", list still " + list);
    }
}
OUTPUT
array store rejected: java.lang.String
list read: 1, list still [1, 2]

Why it behaves this way. An Integer[] really is an Object[] to the compiler, so storing a String compiles; the JVM knows the array's real element type and checks every store, which throws ArrayStoreException. A List<Integer> cannot be assigned to List<Object> at all, because after erasure the list could not check the element. The wildcard view List<? extends Object> gives back safe reading while forbidding writes, so the mistake cannot even be written down.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
List<Object> as a parameter meant to accept any listCallers with List<String> cannot call it; the API forces copies or unchecked casts on every callerList<?> (or a type parameter <T> if T links positions)
Raw List instead of List<?>Type checking disabled; unchecked warnings, and a wrong element fails later as a ClassCastExceptionList<?>; it accepts the same arguments and stays checked
Trying to add to ? extendsCompile error with CAP#1 message, because the list may be a List<Double>Use ? super or an exact type if the method must write
Wildcards in return typesCallers inherit awkward types they can't write to; every caller must deal with an unknown typeReturn exact types; wildcards are for parameters
Wildcards everywhere by habitHard-to-read signatures with no benefit; reviewers stop seeing the ones that matterUse them where callers need flexibility (PECS)
Copying a list to satisfy a rigid parameter (new ArrayList<Number>(ints))An extra allocation per call, and writes to the copy are lost to the callerFix the signature: List<? extends Number> for a producer

8Performance & Production Considerations

Wildcards have no run-time cost; they are erased. Their production relevance is indirect: flexible, correctly typed APIs avoid the raw types and unchecked casts that lead to heap pollution and ClassCastExceptions in unexpected places.

The cost of missing wildcards is visible in profiles and code reviews: defensive copies such as new ArrayList<Number>(ints) made only to call a rigid method, and @SuppressWarnings("unchecked") casts like (List<Number>) (List<?>) ints that compile but can let a wrong element in later. When such patterns cluster around one API, widening its parameters with wildcards removes them at the source, as Figure 6 shows.

A rigid parameter pushes copies and casts onto callers; a wildcard removes them
Figure 6 — A rigid parameter pushes copies and casts onto callers; a wildcard removes them

9Architecture & Design Considerations

Wildcards are an API-design tool. In public library and framework signatures, the right wildcard lets callers pass the collections they already have without copying or casting, which makes a library pleasant to use. Internally, within a class, exact types are simpler. Joshua Bloch's guidance applies: if a parameter is only a producer or only a consumer, use a wildcard (2.3); never return wildcard types; and if a user of your API has to think about wildcards, the API is probably wrong.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is a wildcard in Java generics?

A ? in a type argument, representing an unknown type. It can be unbounded (?), upper-bounded (? extends T) or lower-bounded (? super T). Wildcards appear only in type arguments, never as a type on their own, and they are erased like other type arguments.

Q2L1 · BasicTricky

Is List<Integer> a subtype of List<Number>?

No. Parameterised types are invariant. List<Integer> is a subtype of List<? extends Number>, which is the wildcard type to use when a method should accept both. If it were, a method taking List<Number> could add a Double to what is really a List<Integer>. Arrays allow the equivalent and pay with ArrayStoreException at run time (Example 5).

Q3L2 · IntermediateInternals

Why can't you add an Integer to a List<? extends Number>?

The list might actually be a List<Double> or another subtype; the compiler does not know which, so no specific value except null is guaranteed to be valid. Reading is safe, because every element is at least a Number. To write, the method needs ? super Integer or an exact type.

Q4L2 · IntermediateConcept

What is the difference between List<?>, List<Object> and raw List?

List<?> accepts any parameterised list and is type-checked, allowing only null to be added. List<Object> accepts only lists declared with Object and allows adding anything. Raw List disables generic checking entirely and produces unchecked warnings.

Q5L3 · Senior EngineerInternals

What can you read from a List<? super Integer>, and what can you write?

You can write Integer (and subtypes); you can read only Object, because the element type could be any supertype of Integer up to Object. This is why ? super suits destinations and strategies such as Comparator<? super T> (2.3).

Q6L3 · Senior EngineerTrade-off

Why are generics invariant while arrays are covariant?

Covariant generics would allow inserting wrong types, as arrays do, but generics cannot check element types at run time because of erasure. Invariance plus wildcards keeps all checking at compile time, whereas arrays rely on run-time ArrayStoreException checks.

Q7L3 · Senior EngineerInternals

What is capture conversion, and how does a helper method work around it?

The compiler replaces each wildcard with a fresh unnamed type (CAP#1) for type-checking. Operations that need to name that type — like setting an element read from the same list — fail. Passing the list to a private generic method <T> lets the compiler bind the captured type to T, where the operation type-checks. The public signature stays simple, and no raw type or unchecked cast is needed.

Q8L3 · Senior EngineerDesign

Why should wildcards not appear in return types?

They force every caller to deal with an unknown type — unable to add, often needing casts — which spreads complexity. Parameters benefit from flexibility; return types should be as specific as possible. An exact return type also lets callers keep chaining calls without casts.

Q9L4 · Technical ArchitectDesign

How do you decide wildcard use when designing a shared library API?

Use wildcards on parameters that only produce values (? extends) or only consume them (? super), exact types when a parameter does both, ? when the type is irrelevant, and exact types for return values. Test the API from the caller's perspective with typical collections of subtypes.

Q10L5 · Solution ArchitectScenario

A shared library's generic APIs force teams into unchecked casts and copies. How would you fix it without breaking them?

Audit signatures and add wildcards to parameters following PECS — widening parameter types is source-compatible for callers. Check binary compatibility: erasure of the parameter types usually stays the same, so bytecode signatures do not change. Release as a minor version with migration notes, and add compile tests exercising subtype collections. One caveat: a subclass that overrides such a method with the old signature no longer overrides it after the change; both methods have the same erasure, so javac reports a name clash. Check implementers as well as callers before releasing.

Q11L2 · IntermediateCode

What does this program print?

JAVASuperQuiz.java
public class SuperQuiz {
    public static void main(String[] args) {
        List<? super Integer> sink = new ArrayList<Number>(List.of(2.5));
        sink.add(1);
        Object first = sink.get(0);
        System.out.println(first + " " + first.getClass().getSimpleName());
        System.out.println(sink);
    }
}

It prints 2.5 Double, then [2.5, 1]. The variable is a List<? super Integer>, so adding an Integer compiles, and the underlying ArrayList<Number> already held a Double. Reading gives only an Object, but the object itself is still a Double, as getClass() shows: the wildcard limits what the compiler lets you assume, not what the object is.

Q12L3 · Senior EngineerCode

What does this program print, and why does rotate need a helper?

JAVARotateQuiz.java
public class RotateQuiz {
    static void rotate(List<?> list) { rotateHelper(list); }
 
    private static <T> void rotateHelper(List<T> list) {
        list.add(list.remove(0));             // T names the captured type
    }
 
    public static void main(String[] args) {
        List<String> letters = new ArrayList<>(List.of("a", "b", "c"));
        rotate(letters);
        System.out.println(letters);
        List<?> any = letters;
        any.add(null);                  // the one value any list accepts
        System.out.println(any.size() + " " + letters.get(3));
    }
}

It prints [b, c, a], then 4 null. list.add(list.remove(0)) directly on a List<?> does not compile, because the removed element is only known to be an Object. The helper captures the wildcard as T, so the element and the list share a type. Adding null through the List<?> view is legal, because null belongs to every reference type, so the size becomes 4.

Q13L3 · Senior EngineerScenario

Code review finds many calls like process((List<Event>) (List<?>) orderEvents) with @SuppressWarnings("unchecked"). What is wrong, and what do you propose?

The double cast silences the compiler to get a List<OrderEvent> into a method declared with List<Event>. If process only reads, it is harmless today, but the compiler no longer protects the list: if process ever adds an Event of another kind, the caller's List<OrderEvent> is polluted and fails later. The fix is in the API: declare the parameter List<? extends Event> (or Collection<? extends Event>), remove the casts and suppressions, and add a compile test that passes a subtype list.

Q14L4 · Technical ArchitectTrade-off

A utility method can be written as void printAll(List<?> items) or as <T> void printAll(List<T> items). Which do you choose for a public API?

Both accept the same arguments. The wildcard version says plainly that the method does not care about the element type and keeps the signature short, which is the JDK's usual choice for public methods, such as Collections.shuffle(List<?>). The type-parameter version is needed when the type links positions or when the body must write elements back, as in swap. A good compromise is a public method with a wildcard and a private generic helper that captures it when the body needs the type.

Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Generics are invariant; wildcards add safe flexibility at the use site.
  • ? extends T: read as T, write only null (producer).
  • ? super T: write T, read only Object (consumer).
  • ? : any type, read Object, use type-independent operations.
  • Wildcards belong in parameters, not return types.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.