Command Palette

Search for a command to run...

Back to the lesson: Topic 8.4 — Bounded Type Parameters
Core Java · Example 4 of 4

Comparable<? super T>: max that also works for subclasses

The wildcard ? super T is explained in Topic 8.5. This is the same bound Collections.max and Collections.sort use.

A bound limits which types a type parameter accepts: <T extends Number> means "any Number or subclass", and <T extends Comparable<T>> means "any type that can compare itself". In return, your generic code may call the bound's methods, like doubleValue() or compareTo(), on values of type T.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static <T extends Comparable<? super T>> T min(List<T> list) and test it with integers and strings.

02

Write a class Range<T extends Comparable<? super T>> with contains(T value) and test it with Range<Integer>(1, 10) and Range<String>("b", "m").

03

Write static <T extends Number> double[] toDoubles(List<T> list) and print the result for List.of(1, 2, 3) with Arrays.toString.

Explain it without notes

01

What does an upper bound like <T extends Number> do for the caller and for the code inside the method?

02

Explain <T extends Comparable<T>>. Why is it called a recursive bound, and what problem does Comparable<? super T> solve?

03

What are the rules for multiple bounds, and why does the order matter?

04

How does a bound affect the bytecode of a generic method?

Comparable<? super T>: max that also works for subclasses
Sign in to run this example in your browser.

Expected output

strict, fruits: mango(300g)
flexible, apples: fuji(180g)
flexible, fruits: mango(300g)