Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "Recursive type bound" in Generics mean?

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?

like image 749
Vinoth Kumar C M Avatar asked Sep 12 '11 09:09

Vinoth Kumar C M


People also ask

What is bounded type in generics?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.

What is generic type data?

Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.

What is bound class in Java?

Bound Class By default, IntelliJ IDEA automatically creates a Java class at the same time it creates a new GUI form. The new form automatically binds to the new class via the bind to class property.


1 Answers

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.

like image 77
Péter Török Avatar answered Oct 01 '22 22:10

Péter Török