What does “Recursive type bound” in Generics mean?

感情迁移 提交于 2019-11-30 06:55:49

问题


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?


回答1:


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.




回答2:


There is an entry in the Java Generics FAQ written by Angelika Langer which explains the details of such declaration: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ106



来源:https://stackoverflow.com/questions/7385949/what-does-recursive-type-bound-in-generics-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!