gpt4 book ai didi

java - Java中限制泛型二叉搜索树的类型参数的混淆解释

转载 作者:搜寻专家 更新时间:2023-11-01 02:30:08 25 4
gpt4 key购买 nike

我是泛型(以及 Java 和 Stack Overflow)的新手,我正在学习的教科书中有一点讨论了泛型二叉搜索树的实现(摘录如下)。

The Comparable interface is generic, so let’s consider storing the following type of elements in our search tree:

< T extends Comparable< T>>

This still causes a problem. Suppose that both Dog and Cat are subclasses of a class Mammal and that the Mammal class implements the Comparable interface. Now if we create a binary search tree that stores Mammal objects, then a Dog and Cat could be added, but are not really comparable to each other. So this solution, if used in this particular way, has the same problem as using the nongeneric version of Comparable. A more comprehensive solution, though not as intellectually satisfying, is to write the generic type as:

< T extends Comparable< ? super T>>

This declaration restricts the comparable nature of the element to any superclass of T.

所以我明白了为什么类型参数需要是 Comparable< T> ,但是这本书声称,如果 Mammal 的树,这可能会带来问题s 包含尝试调用 compareTo() 的不同子类型互为方法。那么如果引用类型为CatDog树中的对象是 Mammal ,那么他们不会调用 MammalcompareTo()方法(成为 Comparable< Mammal> ),使其成为有效的比较(仅在 Mammal 级别)?

不明白有什么区别Comparable< ? super T>使,因为那不是一回事,除非Mammal这不是 Comparable然后它回落到 ComparableAnimal 这样的父类(super class)上课什么的?

我可能遗漏了一些东西,比如类型删除的一些令人讨厌的后果,或者会导致比较无法像我想的那样工作的东西。

最佳答案

好的,所以你明白了<T extends Comparable<T>>使用这样的类:

class Mammal extends Comparable<Mammal>

现在你有一个子类Mammal , Cat : class Cat extends Mammal .由于继承Cat还实现了 Comparable<Mammal> ,并且,正如您所说,由于 compareTo(Mammal),它可以与所有哺乳动物(当然包括猫)相提并论。它继承自 Mammal 的方法.

但现在的问题是Cat不适用于绑定(bind) <T extends Comparable<T>> ,因为 Cat不执行 Comparable<Cat> .你不能通过 Cat 来解决这个问题实现 Comparable<Cat> ,因为您只能使用一种类型参数实现接口(interface)。

但从概念上讲,对 Cat 的列表进行排序是没有问题的, 自 Cat s 可以与其他 Cat 进行比较s(他们可以比所有哺乳动物,比较笼统;但重点是他们可以比猫)。所以问题是我们的限制太严格了。

<T extends Comparable<? super T>>解决了这个问题,并允许 Cat要使用的。回顾 PECS 规则——生产者 extends消费者super .好吧,Comparable 是消费者而不是生产者,因为您将 T 类型的参数传递给它的 compareTo。方法(消费),但没有方法需要返回类型 T(生产)。因此,一个 super通配符是合适的。

关于java - Java中限制泛型二叉搜索树的类型参数的混淆解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11493081/

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