Video in progress
What do signatures like <T extends Comparable<? super T>> mean, and why is Enum<E extends Enum<E>> written that way?
The first one means a T can be compared with itself or with its supertype. The second is a recursive generic, so that methods like compareTo work with exactly that concrete enum type.
📖 Answer
Take the signature of Collections.max:
static <T extends Comparable<? super T>> T max(Collection<? extends T> c)
Why not a plain T extends Comparable<T>? Because Comparable is often implemented once in a parent class:
class Money implements Comparable<Money> { ... }
class Usd extends Money { } // not Comparable<Usd>!
List<Usd> list = ...;
Collections.max(list); // works thanks to ? super T
Usd is a Comparable<Money>, and Money is a supertype of Usd, so the condition holds.
A recursive generic (F-bounded) means the type parameter appears in its own bound:
abstract class Enum<E extends Enum<E>> implements Comparable<E> {
public final int compareTo(E o) { ... }
}
As a result, Status.A.compareTo(Color.RED) doesn't compile.
The same pattern is used in builder hierarchies:
abstract class Builder<B extends Builder<B>> {
B name(String n) { this.name = n; return self(); }
abstract B self();
}
That way the child builder's methods don't "drop" to the parent type in the chain. In practice, being able to read this syntax is enough; you'd only need to write it yourself in a library API.
Sign up to mark studied questions and save your progress.