什么是“递归类型绑定”在泛型中是什么意思? [英] What does "Recursive type bound" in Generics mean?
问题描述
书中有这样的一段:
尽管相对较少,但允许类型参数受涉及该类型参数本身的某个表达式限制的情况是允许的。这就是所谓的递归类型绑定。
和这个:
//使用递归类型绑定来表达相互可比性
public static< T extends Comparable< T>> T max(List< T> list){...}
什么是递归类型绑定,上述代码是否有助于实现相互可比性?
什么是递归类型绑定
这是:< T延伸Comparable< T>>
请注意,类型参数 T
也是超级接口 Comparable< T>
的签名的一部分。
以上代码如何帮助实现相互可比性?
它确保您只能比较 T
类型的对象。如果没有绑定类型, Comparable
会比较任何两个 Object
s。通过绑定类型,编译器可以确保只有两个 T
类型的对象进行比较。
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?
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.
这篇关于什么是“递归类型绑定”在泛型中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!