Code Snippets
/

Bounded Generics with extends

Bounded Generics with extends

Bounded type parameters and wildcards (`<T extends Number>`, `<? extends Number>`, `<? super Integer>`) are how Java balances type safety with API flexibility. This snippet shows an upper-bounded type parameter for arithmetic, the producer-extends-consumer-super (PECS) rule with wildcards, and a comparator-driven generic max function. Get these right and your collection APIs will accept everything the caller reasonably wants to pass.

Java
Medium
3 snippets
java-generics
generics
type-system

745 views

9

import java.util.*;
import java.util.Comparator;

public class Main {
    // T is restricted to Number subclasses, so .doubleValue() is safe.
    static <T extends Number> double sum(List<T> list) {
        double total = 0;
        for (T n : list) total += n.doubleValue();
        return total;
    }

    public static void main(String[] args) {
        List<Integer> ints = Arrays.asList(1, 2, 3);
        List<Double> dbls = Arrays.asList(1.5, 2.5);
        System.out.println("sum ints = " + sum(ints));
        System.out.println("sum dbls = " + sum(dbls));
        // sum(Arrays.asList("a")) would not compile: String is not a Number.
    }
}

Declaring <T extends Number> constrains the type parameter so the method body can call any Number member like doubleValue(). Without the bound, T would be Object and you would not be able to do arithmetic on it. The single bound is the common case; multiple bounds are written <T extends Number & Comparable<T>> (only the first may be a class). Use this when the method genuinely needs to call a method on T; if it only stores or returns the value, a wildcard is usually a better fit (next accordion).