Java Wildcards

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 163 of 306

The Problem Wildcards Solve

Generic types are invariant: even though Integer is a subtype of Number, List<Integer> is not a subtype of List<Number> (Generic Types lesson). That rule prevents bugs, but it also makes some perfectly reasonable methods too restrictive:

static double sumStrict(List<Number> values) { ... }

List<Integer> ints = new ArrayList<>();
sumStrict(ints);   // compile error: List<Integer> cannot be converted to List<Number>

A method that only reads numbers from a list should accept a list of integers, a list of doubles, or a list of any other kind of number. Wildcards express exactly that. A wildcard is a ? used as a type argument, meaning "some type, not known exactly":

WildcardRead asAccepts
List<?>a list of some unknown typeList<String>, List<Integer>, any list
List<? extends Number>a list of some type that is a NumberList<Number>, List<Integer>, List<Double>, ...
List<? super Integer>a list of some type that is a supertype of IntegerList<Integer>, List<Number>, List<Object>

Wildcards appear in variable and parameter types. You never create an object with a wildcard (new ArrayList<?>() is illegal); you use them to say what a method or variable accepts.

The Three Kinds of Wildcard

import java.util.*;

public class W1 {
    static double sumStrict(List<Number> values) {
        double t = 0;
        for (Number n : values) t += n.doubleValue();
        return t;
    }

    static double sum(List<? extends Number> values) {
        double t = 0;
        for (Number n : values) t += n.doubleValue();
        return t;
    }

    static void printAll(Collection<?> items) {
        System.out.println(items.size() + " items: " + items);
    }

    static void addDefaults(List<? super Integer> target) {
        target.add(10);
        target.add(20);
    }

    public static void main(String[] args) {
        List<Integer> ints = List.of(1, 2, 3);
        List<Double> prices = List.of(99.5, 0.5);
        System.out.println(sum(ints) + " " + sum(prices));

        printAll(List.of("a", "b"));
        printAll(Set.of(42));

        List<Number> numbers = new ArrayList<>();
        List<Object> objects = new ArrayList<>(List.of("header"));
        addDefaults(numbers);
        addDefaults(objects);
        System.out.println(numbers + " " + objects);
    }
}

Output:

6.0 100.0
2 items: [a, b]
1 items: [42]
[10, 20] [header, 10, 20]

Upper-bounded: ? extends T

sum(List<? extends Number>) accepts a List<Integer> and a List<Double>. Inside the method, every element can be read as a Number, because whatever the actual element type is, it's some subtype of Number.

Unbounded: ?

printAll(Collection<?>) accepts any collection. Elements can only be read as Object, which is enough for methods that use only Object's methods (toString, equals) or the collection's own methods (size, isEmpty, clear). Collection<?> is the type-safe replacement for the raw type Collection.

Lower-bounded: ? super T

addDefaults(List<? super Integer>) accepts a List<Integer>, a List<Number> or a List<Object>. Whatever the actual element type is, it's a supertype of Integer, so adding an Integer is always safe.

What You Can Read and Write

Each wildcard trades away one ability for flexibility. The compiler enforces this:

import java.util.*;

public class E1 {
    static double sumStrict(List<Number> values) { return 0; }

    static void broken(List<? extends Number> values, List<? super Integer> sink) {
        values.add(3);
        Integer first = sink.get(0);
    }

    public static void main(String[] args) {
        sumStrict(List.of(1, 2, 3));
        List<Integer> ints = new ArrayList<>();
        sumStrict(ints);
    }
}
E1.java:7: error: incompatible types: int cannot be converted to CAP#1
        values.add(3);
                   ^
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Number from capture of ? extends Number
E1.java:8: error: incompatible types: CAP#1 cannot be converted to Integer
        Integer first = sink.get(0);
                                ^
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object super: Integer from capture of ? super Integer
E1.java:14: error: incompatible types: List<Integer> cannot be converted to List<Number>
        sumStrict(ints);
                  ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors
  • You can't add to a List<? extends Number> (except null). The list might really be a List<Double>; adding the Integer 3 would corrupt it. The compiler represents the unknown element type as CAP#1 (a captured type variable) and can't prove that 3 is a CAP#1.
  • Reading from a List<? super Integer> gives only Object. The list might be a List<Object> containing strings, so its elements can't be assumed to be Integer.
  • Note that line 12, sumStrict(List.of(1, 2, 3)), compiled: List.of is generic, and the compiler inferred List<Number> from the parameter type. Only an existing List<Integer> variable (line 14) is rejected.

Reading in practice:

import java.util.*;

public class Read {
    public static void main(String[] args) {
        List<? extends Number> producer = List.of(1, 2.5, 3L);
        Number n = producer.get(1);
        System.out.println("read from ? extends: " + n);

        List<? super Integer> consumer = new ArrayList<Number>(List.of(7.5));
        consumer.add(5);
        Object o = consumer.get(0);
        System.out.println("read from ? super: " + o + " (" + o.getClass().getSimpleName() + "), list " + consumer);
    }
}

Output:

read from ? extends: 2.5
read from ? super: 7.5 (Double), list [7.5, 5]
Read elements asAdd elements
List<T>TT
List<? extends T>TNothing (only null)
List<? super T>ObjectT (and its subtypes)
List<?>ObjectNothing (only null)

The consumer list really is a List<Number> containing a Double; the code could add an Integer to it, but reading gave back an Object — the only type that's safe for every possible supertype of Integer.

PECS: Producer Extends, Consumer Super

A memorable rule (from Effective Java) decides which wildcard to use for a parameter:

  • If the parameter produces values your method reads → use ? extends T.
  • If the parameter consumes values your method writes → use ? super T.
  • If it does both → use plain T, no wildcard.
import java.util.*;
import java.util.function.*;

public class Pecs {
    static <T> void copy(List<? extends T> source, List<? super T> target) {
        for (T item : source) target.add(item);
    }

    static <T> List<T> filter(Collection<? extends T> items, Predicate<? super T> keep) {
        List<T> out = new ArrayList<>();
        for (T item : items) if (keep.test(item)) out.add(item);
        return out;
    }

    public static void main(String[] args) {
        List<Integer> marks = List.of(91, 45, 78);
        List<Double> fees = List.of(4999.0, 2999.0);
        List<Number> all = new ArrayList<>();
        copy(marks, all);
        copy(fees, all);
        System.out.println("all numbers: " + all);

        Predicate<Number> positive = n -> n.doubleValue() > 50;
        Predicate<Object> notNull = Objects::nonNull;
        List<Integer> passed = filter(marks, positive);
        List<Integer> present = filter(marks, notNull);
        System.out.println("passed: " + passed + ", present: " + present.size());

        List<Integer> sorted = new ArrayList<>(marks);
        Comparator<Number> byDouble = Comparator.comparingDouble(Number::doubleValue);
        sorted.sort(byDouble);
        System.out.println("sorted with Comparator<Number>: " + sorted);
    }
}

Output:

all numbers: [91, 45, 78, 4999.0, 2999.0]
passed: [91, 78], present: 3
sorted with Comparator<Number>: [45, 78, 91]
  1. copy: the source produces items (? extends T), the target consumes them (? super T). Integers and doubles can both be copied into a List<Number>. Without wildcards, copy would require all three lists to have exactly the same element type. The JDK's Collections.copy(List<? super T> dest, List<? extends T> src) is declared this way.
  2. filter: the items are produced (? extends T); the predicate consumes each item to test it (? super T). So a List<Integer> can be filtered with a Predicate<Number> or even a Predicate<Object> — a general predicate works for more specific elements.
  3. List.sort(Comparator<? super E>): a Comparator<Number> consumes numbers, so it can sort a List<Integer>. This is the same idea that made Comparable<? super T> necessary for LocalDate in the Bounded Types lesson.

Functional interfaces follow the rule naturally: a Function<T, R> parameter is usually declared Function<? super T, ? extends R> — it consumes Ts and produces Rs. That's why the JDK's signatures, such as Stream.map(Function<? super T, ? extends R> mapper), look the way they do.

Wildcard Capture and Helper Methods

Because the element type of a List<?> is unknown, the compiler won't even let you put back an element you just took out of the same list:

import java.util.*;

public class CapErr {
    static void swapFirstLast(List<?> list) {
        Object first = list.get(0);
        list.set(0, list.get(list.size() - 1));
    }
}
CapErr.java:6: error: incompatible types: Object cannot be converted to CAP#1
        list.set(0, list.get(list.size() - 1));
                            ^
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object from capture of ?

The standard fix is a private generic helper method that "captures" the wildcard as a named type parameter:

import java.util.*;

public class Capture {
    static void swapFirstLast(List<?> list) {
        swapHelper(list);
    }

    private static <T> void swapHelper(List<T> list) {
        T first = list.get(0);
        list.set(0, list.get(list.size() - 1));
        list.set(list.size() - 1, first);
    }

    public static void main(String[] args) {
        List<String> cities = new ArrayList<>(List.of("Chennai", "Madurai", "Salem"));
        swapFirstLast(cities);
        System.out.println(cities);
        List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4));
        swapFirstLast(nums);
        System.out.println(nums);
    }
}

Output:

[Salem, Madurai, Chennai]
[4, 2, 3, 1]

When swapHelper(list) is called, the compiler infers T as the captured unknown type. Inside the helper, the elements have a name (T), so reading and writing them is allowed. The public method keeps the simple List<?> signature; the JDK's Collections.swap(List<?> list, int i, int j) and Collections.reverse(List<?>) use this technique.

Wildcard or Type Parameter?

Both of these accept a list of any numbers:

static double sum(List<? extends Number> values)
static <T extends Number> double sum(List<T> values)

Guidelines:

  • Use a wildcard when the type is used only once in the signature and you don't need to name it — it's simpler to read.
  • Use a type parameter when the same type must appear in several places to relate them — for example, static <T> T lastOf(List<T> list) links the return type to the element type, and static <T> void copy(List<? extends T> src, List<? super T> dst) links two parameters.
  • Avoid wildcards in return types. A method returning List<? extends Number> forces every caller to deal with the wildcard's restrictions. Return a concrete type such as List<Number> or List<T> instead.

Practical Example: A Type-Safe Event Bus

Applications often publish events — an order was placed, a user signed up — to which other parts of the system subscribe: send an invoice, send a welcome email, write an audit log. A small event bus shows several wildcard rules working together, including handlers that are more general than the event they handle.

import java.time.Instant;
import java.util.*;
import java.util.function.Consumer;

public class Events {
    interface Event { Instant at(); }
    record OrderPlaced(String orderId, double amount, Instant at) implements Event { }
    record UserSignedUp(String email, Instant at) implements Event { }

    static class EventBus {
        private final Map<Class<?>, List<Consumer<? super Event>>> handlers = new LinkedHashMap<>();

        <E extends Event> void subscribe(Class<E> type, Consumer<? super E> handler) {
            handlers.computeIfAbsent(type, t -> new ArrayList<>())
                    .add(event -> handler.accept(type.cast(event)));
        }

        void publish(Event event) {
            for (Map.Entry<Class<?>, List<Consumer<? super Event>>> entry : handlers.entrySet()) {
                if (entry.getKey().isInstance(event)) {
                    entry.getValue().forEach(h -> h.accept(event));
                }
            }
        }

        void publishAll(Collection<? extends Event> events) {
            for (Event e : events) publish(e);
        }
    }

    public static void main(String[] args) {
        EventBus bus = new EventBus();
        List<String> audit = new ArrayList<>();
        Consumer<Event> auditor = e -> audit.add(e.getClass().getSimpleName() + "@" + e.at());
        Consumer<Object> printer = o -> System.out.println("  got " + o);

        bus.subscribe(OrderPlaced.class, o -> System.out.println("  invoice for " + o.orderId() + ": Rs " + o.amount()));
        bus.subscribe(UserSignedUp.class, u -> System.out.println("  welcome mail to " + u.email()));
        bus.subscribe(Event.class, auditor);
        bus.subscribe(UserSignedUp.class, printer);

        Instant t = Instant.parse("2026-11-15T10:00:00Z");
        List<OrderPlaced> orders = List.of(new OrderPlaced("O-1", 2500, t), new OrderPlaced("O-2", 800, t.plusSeconds(5)));
        bus.publishAll(orders);
        bus.publish(new UserSignedUp("asha@gocourse.in", t.plusSeconds(9)));
        System.out.println("audit: " + audit);
    }
}

Output:

  invoice for O-1: Rs 2500.0
  invoice for O-2: Rs 800.0
  welcome mail to asha@gocourse.in
  got UserSignedUp[email=asha@gocourse.in, at=2026-11-15T10:00:09Z]
audit: [OrderPlaced@2026-11-15T10:00:00Z, OrderPlaced@2026-11-15T10:00:05Z, UserSignedUp@2026-11-15T10:00:09Z]

Where the wildcards matter:

  1. subscribe(Class<E> type, Consumer<? super E> handler) — a handler consumes events, so ? super E lets a general handler subscribe to a specific event type. printer, a Consumer<Object>, subscribes to UserSignedUp; auditor, a Consumer<Event>, subscribes to all events. With Consumer<E>, both would be rejected.
  2. Lambdas get the precise type. For subscribe(OrderPlaced.class, o -> ...), the compiler infers E = OrderPlaced, so o.orderId() and o.amount() are available inside the lambda without casts.
  3. Class<E> as a runtime type token. Because generic types are erased at runtime (next lesson), the bus can't otherwise know which events a handler wants. The Class object is stored as the map key; isInstance checks whether an event matches (so subscribing to Event.class matches every event), and type.cast(event) performs a checked cast before calling the typed handler.
  4. publishAll(Collection<? extends Event>) — the collection produces events, so a List<OrderPlaced> is accepted. With Collection<Event>, the caller would have to copy it into a new list first.
  5. Storage uses Consumer<? super Event>. Each stored handler is a small adapter lambda that accepts any Event, casts it and forwards it, so handlers for different event types can live in one map safely.

Frameworks such as Spring's application events and Guava's EventBus use these same techniques — class tokens for dispatch and ? super for handler flexibility.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Wildcards and get answers drawn from it.

Signed-in readers only.