Java language

Wildcard capture

A generic helper can name the captured unknown type for type-safe operations on the same list.

Formal Syntax & Structure

java syntaxjava
static <T> void swap(List<T> items)

Working Example

Example Snippetjava
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);    }}
Java Reference