Java

Generic Method + Bounded Type Parameters

admin by @admin ADMIN
Jun 18, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A method can have its own type parameter independent of the class. `<T extends Comparable<T>>` constrains T to types that can be compared.
Java
Raw
import java.util.*;

class Util {
    // Generic method — type inferred from the argument
    public static <T> T firstOrNull(List<T> items) {
        return items.isEmpty() ? null : items.get(0);
    }

    // Bounded — T must be Comparable to itself
    public static <T extends Comparable<T>> T max(List<T> items) {
        T best = items.get(0);
        for (T x : items) if (x.compareTo(best) > 0) best = x;
        return best;
    }

    // Multiple bounds with &
    public static <T extends Number & Comparable<T>> T maxNumber(List<T> nums) {
        return max(nums);
    }

    public static void main(String[] args) {
        System.out.println(firstOrNull(List.of("a", "b", "c")));   // a
        System.out.println(max(List.of(3, 1, 4, 1, 5)));           // 5
        System.out.println(max(List.of("apple", "banana", "cherry"))); // cherry
    }
}
Tags

Save your own code snippets

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