Java Snippet

Bounded Generics with extends

Difficulty: Medium

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.

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

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).