How would you implement a generic class with multiple type parameters and bounded type parameters (like <T extends Comparable<T>>), and what does this specific bound enable?
Short answer
A class can declare multiple type parameters (class Pair ), and a bounded type parameter ( ) restricts what types can be substituted for T to only SomeType or its subtypes, letting the generic class/method call methods declared on that bound directly on values of type T…
Advertisement
AModel answer
A class can declare multiple type parameters (class Pair<K, V>), and a bounded type parameter (<T extends SomeType>) restricts what types can be substituted for T to only SomeType or its subtypes, letting the generic class/method call methods declared on that bound directly on values of type T (something impossible with an unbounded T, which the compiler only knows to be Object-compatible) -- the specific recursive bound <T extends Comparable<T>> (sometimes called the 'curiously recurring generic pattern' in this context) is a common idiom ensuring T is comparable specifically to itself, enabling generic methods like a maximum-finder that need to call compareTo() on the elements.
public class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) { this.key = key; this.value = value; }
public K getKey() { return key; }
public V getValue() { return value; }
}
public static <T extends Comparable<T>> T max(List<T> list) {
T max = list.get(0);
for (T item : list) {
if (item.compareTo(max) > 0) { max = item; } // compareTo() only callable because of the bound
}
return max;
}Real-world example
A generic sorting/comparison utility method requires its type parameter to be bounded by Comparable<T> specifically so it can call compareTo() directly on elements of that generic type, a call that would be a compile error against an unbounded generic type parameter that could be any arbitrary Object-compatible type.
Likely follow-ups
- How would you write a bound requiring T to implement multiple interfaces simultaneously (like both Comparable and Serializable)?
- What's the difference between a bounded type parameter and a bounded wildcard, given both use the 'extends' keyword?
Related topics