Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Exceptions and Generics

    Bounded Types

    "Box of — must be something that can be measured." You can fill the blank with apples or bananas, not with "happiness".

    Chapter 8 of 102 min read

    The Plain Picture#

    "Box of ____ — must be something that can be measured." You can fill the blank with apples or bananas, not with "happiness".

    The Real Name#

    A bounded type parameter restricts which types are allowed, so the code inside can use their methods. <T extends X> means "T must be X or a subtype of X" (for interfaces too — generics always say extends, never implements).

    Java
    static <T extends Comparable<T>> T maxOf(List<T> items) {
        // T must be comparable to itself
        T best = items.get(0);
        for (T x : items) {
            if (x.compareTo(best) > 0) best = x; // compareTo is allowed BECAUSE of the bound
        }
        return best;
    }
    
    System.out.println(
        maxOf(List.of(72, 95, 60)) + " " + maxOf(List.of("Priya", "Aisha", "Rahul"))
    );
    // 95 Rahul

    One method works for integers, strings, and any class implementing Comparable — and the compiler rejects types that can't be compared. Without the bound, x.compareTo(...) wouldn't compile, because an unknown T might not have that method.

    Multiple bounds: <T extends Number & Comparable<T>> (a class first, then interfaces, joined by &).

    Check yourself

    2 questions
    1

    What does <T extends Comparable<T>> allow the method to do?

    Show answer

    Call compareTo on values of type T, and reject types that aren't comparable.

    2

    Why does maxOf(List.of("Priya", "Aisha", "Rahul")) return "Rahul"?

    Show answer

    Strings compare in dictionary order, and "Rahul" comes last.