0Pricing
Java Academy · Lesson

Wildcards in APIs

Design flexible generic methods.

Designing Flexible Methods

Wildcards are mainly a tool for API designers. A well-placed wildcard lets callers pass more types without casts.

The goal: maximum flexibility for callers, full type safety inside.

import java.util.List;

public class Main {
    static double total(List<? extends Number> items) {
        double sum = 0;
        for (Number n : items) sum += n.doubleValue();
        return sum;
    }
    public static void main(String[] args) {
        System.out.println(total(List.of(1, 2, 3)));
        System.out.println(total(List.of(1.5, 2.5)));
    }
}

Unbounded Wildcards

List<?> is an unbounded wildcard: a list of some unknown type.

Use it when your method does not care about the element type, for example counting elements or checking emptiness.

import java.util.List;

public class Main {
    static int size(List<?> any) {
        return any.size();
    }
    public static void main(String[] args) {
        System.out.println(size(List.of("a", "b")));
        System.out.println(size(List.of(1, 2, 3)));
    }
}

All lessons in this course

  1. Upper Bounded Wildcards
  2. Lower Bounded Wildcards
  3. The PECS Principle
  4. Wildcards in APIs
← Back to Java Academy