Skip to content

Wildcards & Variance

The Course
•
15 min study

A List<Task> is not a List<Named>, even when Task implements Named. If it were, someone could insert a different Named implementation into a list that promises only Tasks. This property is called invariance. Wildcards describe a narrower permission: read compatible values without promising you can add arbitrary ones.

The question mark ? means “some type that is not named here.” It is not a missing value or a request to turn type checking off. A named T connects types across a method or class; a wildcard describes what this particular parameter can accept.

Start with the error wildcards exist to fix

A Task is a Named, so it seems a List<Task> should be usable wherever a List<Named> is expected. Predict whether this compiles:

Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<Task> tasks = new ArrayList<>();
        tasks.add(new Task());
        printTitles(tasks);
    }

    static void printTitles(List<Named> source) {
        for (Named value : source) {
            System.out.println(value.title());
        }
    }
}

interface Named {
    String title();
}

final class Task implements Named {
    public String title() {
        return "Read";
    }
}

It does not:

Text
Main.java:8: error: method printTitles in class Main cannot be applied to given types;
        printTitles(tasks);
        ^
  required: List<Named>
  found:    List<Task>

The reason: a method taking List<Named> is allowed to call source.add(new Label()) with any other Named. If Java let you pass your List<Task>, your task list would end up holding a Label. So a List<Task> is not a List<Named>, even though a Task is a Named. To fix the call, change the parameter to List<? extends Named>, which means "a list of some Named type, that I will only read". The example below is exactly that fix.

Work through the example

List<? extends Named> accepts a list of an unknown specific subtype of Named. Reading gives at least Named, so title() is available. Adding a new Task is unsafe because the actual list might be List<Label>. Do not defeat that restriction with a cast.

Use an extends wildcard for a source you read. It does not freeze the list; for example, clear() is still a List operation. Your method's contract must promise not to mutate it if that is the behavior you intend. A wildcard is not an ownership mechanism.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<Task> tasks = new ArrayList<>();
        tasks.add(new Task());
        printTitles(tasks);
    }

    static void printTitles(List<? extends Named> source) {
        for (Named value : source) {
            System.out.println(value.title());
        }
    }
}

interface Named {
    String title();
}

final class Task implements Named {
    public String title() {
        return "Read";
    }
}
Check your prediction
Text
Read

Compare the behavior

List<? super String> is a destination that can accept Strings: it may be a List<String> or a List<Object>. Reading an arbitrary element gives only Object because that list could also contain other objects. The useful memory aid is “producer extends, consumer super,” but trace the permissions rather than memorizing the phrase alone.

Trace the changed case Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<Object> destination = new ArrayList<>();
        addTitle(destination);
        System.out.println(destination);
    }

    static void addTitle(List<? super String> destination) {
        destination.add("Read");
    }
}
Check your prediction
Text
[Read]

Reason about permission rather than spelling

Start with a source containing Task objects. A List<? extends Named> reference allows reading each value as Named, since every possible element type meets that capability. It does not allow inserting an arbitrary Named: the hidden element type could be a different implementation. The restriction protects the original list's promise.

A destination List<? super Named> can accept any Named value because its actual element type is Named or a supertype such as Object. An arbitrary element read from that destination is only guaranteed to be Object; the list could already contain another kind of value.

Use this source/destination distinction together with a no-mutation contract. extends does not remove clear or other collection operations, and a writable element can still change. Today's copying operation reads one container and appends to a separate compatible destination. Distinct source and destination containers also avoid invalidating a traversal while it appends.

Practice independently

Exercise

Wildcards & Variance: practice

Write copyNames(List<? extends Named> source, List<? super Named> destination) that appends every source element in order. The nonnull arguments must be distinct mutable containers with nonnull elements. Use Named with title(), and Task implementing it. Demonstrate a List<Task> source containing Read and Test copied into a List<Named> destination. Print each destination title and then the unchanged source size (2). No casts are needed.

Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.

Your workspace Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        System.out.println("Implement Named, Task and copyNames");
    }
}
Hint 1: the idea

The source may contain a specific implementation of Named while the destination accepts any Named value. Use each side only through the permission its wildcard provides.

Hint 2: a first step

Iterate as Named over source and append each value to the destination; the element type of the source can remain Task.

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<Task> source = new ArrayList<>();
        source.add(new Task("Read"));
        source.add(new Task("Test"));
        List<Named> destination = new ArrayList<>();
        copyNames(source, destination);
        for (Named value : destination) {
            System.out.println(value.title());
        }
        System.out.println(source.size());
    }

    static void copyNames(List<? extends Named> source, List<? super Named> destination) {
        for (Named value : source) {
            destination.add(value);
        }
    }
}

interface Named {
    String title();
}

final class Task implements Named {
    private final String title;

    Task(String title) {
        this.title = title;
    }

    public String title() {
        return title;
    }
}

Expected output:

Text
Read
Test
2

Change it and test again

Try passing a List<Object> as destination: it can accept Named values, so the copy still works. Then try reading destination.get(0) into a Named variable inside copyNames. The compiler only guarantees Object for an arbitrary read through this super wildcard. Restore the code. Add another Named implementation to a List<Named> source and copy it without changing copyNames. This makes the subtype relationship meaningful; a String-only extends example would have no subclasses because String is final.

Explain before moving on

Which operations are promised by extends and by super? Why does a read-oriented method still need a documented no-mutation rule?

Was this article helpful?

Your response is saved on this device.