What does "Recursive type bound" in Generics mean?

Vinoth Kumar C M picture Vinoth Kumar C M · Sep 12, 2011 · Viewed 7.2k times · Source

I am reading the chapter on Generics from Effective Java[Item 27].

There is this paragraph in the book:

It is permissible, though relatively rare, for a type parameter to be bounded by some expression involving that type parameter itself. This is what’s known as a recursive type bound.

and this:

// Using a recursive type bound to express mutual comparability
public static <T extends Comparable<T>> T max(List<T> list) {...}

What is recursive type bound and how does the above piece of code help achieve mutual comparability?

Answer

P&#233;ter T&#246;r&#246;k picture Péter Török · Sep 12, 2011

What is recursive type bound

This: <T extends Comparable<T>>

Note that the type parameter T is also part of the signature of the super interface Comparable<T>.

and how does the above piece of code help achieve mutual comparability?

It ensures that you can only compare objects of type T. Without the type bound, Comparable compares any two Objects. With the type bound, the compiler can ensure that only two objects of type T are compared.