Java

Wildcards — extends vs super (PECS)

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Producer-Extends, Consumer-Super. `? extends T` is read-only (you can take items OUT). `? super T` is write-only (you can put items IN). Lets generic APIs accept a wider range of types.
Java
Raw
import java.util.*;

class Util {
    // PRODUCES T → use extends
    // Accepts List<Integer>, List<Number>, etc — reads but cannot add
    public static double sum(List<? extends Number> nums) {
        double total = 0;
        for (Number n : nums) total += n.doubleValue();
        return total;
    }

    // CONSUMES T → use super
    // Accepts List<Integer>, List<Number>, List<Object> — adds but cannot safely read
    public static void addInts(List<? super Integer> sink) {
        sink.add(1);
        sink.add(2);
        sink.add(3);
    }

    public static void main(String[] args) {
        List<Integer> ints   = List.of(1, 2, 3);
        List<Double>  dbls   = List.of(1.5, 2.5);
        System.out.println(sum(ints));        // 6.0
        System.out.println(sum(dbls));        // 4.0

        List<Number> sink = new ArrayList<>();
        addInts(sink);
        System.out.println(sink);              // [1, 2, 3]
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.