Variance and capture
What you will learn
Variance describes when related type arguments produce related parameterized types. Java generic classes are invariant by default; wildcards express useful read/write relationships. Capture conversion lets a helper method work with the same unknown element type consistently.
- Distinguish generic invariance from array covariance.
- Use a generic helper to capture an unknown element type.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed. List, Map and Set operations used here are brief previews of later collection chapters.
Accept two different numeric lists for reading
import java.util.*;public class Main { static Number first(List<? extends Number> items) { return items.get(0); } public static void main(String[] args) { List<Integer> integers = List.of(3); List<Double> doubles = List.of(1.5); System.out.println(first(integers)); System.out.println(first(doubles)); }}Expected output:
31.5Both lists fit the wildcard contract; the method requires a nonempty list and cannot insert an arbitrary Number.
Rules and mental model
Even though Integer extends Number, List<Integer> does not extend List<Number>. An extends wildcard provides a safe common view. Arrays are covariant, so an Integer[] can be assigned to Number[], but an incompatible store is checked at runtime and throws ArrayStoreException. Generic collections instead reject many incompatible operations at compile time. List<?> means a list of some unknown element type. A helper taking List<T> can bind a single captured type and use it consistently for reads and writes. Capturing a wildcard does not let the caller choose its unknown type. Captures of two independent wildcard arguments need not be the same; use a shared type parameter or explicit producer/consumer relationship for transfer. A mutable list is required for operations using set; the examples explicitly create ArrayList instances.
Capture one unknown type to swap elements
import java.util.*;public class Main { static void swapFirstTwo(List<?> items) { swap(items); } static <T> void swap(List<T> items) { if (items.size() < 2) return; T first = items.get(0); items.set(0, items.get(1)); items.set(1, first); } public static void main(String[] args) { List<String> labels = new ArrayList<>(List.of("A", "B")); List<Integer> counts = new ArrayList<>(List.of(1, 2)); swapFirstTwo(labels); swapFirstTwo(counts); swapFirstTwo(new ArrayList<>()); System.out.println(labels); System.out.println(counts); }}Expected output:
[B, A][2, 1]The helper binds T to the captured element type, and puts back only values retrieved from that same list. Empty or singleton lists require no changes.
Common mistakes
Do not cast List<?> to List<Object> just to perform a swap. A helper that uses one T can preserve the element type without unchecked conversions. Avoid assuming covariance of arrays makes all assignments safe.
Practice
Implement duplicateFirst(List<?>) via a generic helper that appends the first element if the list is not empty. Test a mutable list of two strings, a mutable list of one integer and an empty mutable list.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Variance and capture — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
Which assignment is rejected?
Why does the swap helper use List<T>?
What happens when storing a Double into a Number[] referring to an Integer[]?