gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:21:24 26 4
gpt4 key购买 nike

考虑

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com