java - 泛型 Java 中关键字通过类型 Parameter<T> 扩展

标签 java generics extends

考虑

Gen<T>

所以,当我写这样的东西

Gen<Integer> someRef = new Gen<>();
Gen<String> someRef = new Gen<>();

据我了解,

The Java compiler does not actually create different versions of Gen, or of any other generic class. Although it’s helpful for me to think in these terms, it is not what actually happens. Instead, the compiler removes all generic type information, substituting the necessary casts, to make my code behave as if a specific version of Gen were created. Thus, there is really only one version of Gen that actually exists in my program. The process of removing generic type information is called erasure.

现在考虑这个,

interface MinMax<T extends Comparable<T>> {

In general, a generic interface is declared in the same way as is a generic class. In this case, the type parameter is T, and its upper bound is Comparable, which is an interface defined by java.lang. A class that implements Comparable defines objects that can be ordered. Thus, requiring an upper bound of Comparable ensures that MinMax can be used only with objects that are capable of being compared. Notice that Comparable is also generic. (It was retrofitted for generics by JDK 5.) It takes a type parameter that specifies the type of the objects being compared.

接下来,MinMax是由MyClass实现的。

注意 MyClass 的声明,如下所示:

class MyClass<T extends Comparable<T>> implements MinMax<T> {

我的困惑来了, 当我写这样的东西时,

MyClass<Integer>  ......

类型参数 T 将替换为 Integer。或者说任何其他版本(取决于我将操作的对象类型)。

我很清楚类实现了接口(interface)。综上所述,上面的案例不也是这样吗

class MyClass<Integer(or some other version) extends Comparable<Integer>> implements MinMax<Integer> {

那么,这里的类为什么要扩展接口(interface)呢,

Integer(or some other version) extends Comparable<Integer>

我确信,我对上述上下文的理解是不正确的。请详细说明一下?

最佳答案

原因是在泛型中,关键字 extends 用于不同的上下文

在泛型中,T extends Something 表示 T 将是 Something 的子类实现Something(在接口(interface)的情况下)。绑定(bind)的类型并不重要(类或接口(interface)) - 重要的是 T 是所提供绑定(bind)的子类型

更多信息:

关于java - 泛型 Java 中关键字通过类型 Parameter<T> 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26488639/

相关文章:

java - 访问内部类的局部变量需要声明为final

java - java中的通用迭代器实现

java - 类数组,特定类的子类

java - android访问扩展类中的对象

扩展时迭代其自身类型的 Java 类

java - 谷歌云翻译和Java编码错误

java - 使用java验证outlook邮箱地址

java - J2EE 7 Rest 客户端中的属性而不是值

generics - Ada 通用包扩展

java - 我如何在扩展类构造函数内部调用抽象类的构造函数