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?
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.
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.
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.
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 Object
s. With the type bound, the compiler can ensure that only two objects of type T
are compared.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With