首页 > 解决方案 > 泛型和通配符

问题描述

我正在设计一个 BinarySearchTree 的实现,尽管我遇到了一个我以前没有遇到过的问题。我对如何解决这个问题也知之甚少:

The type K is not a valid substitute for the bounded parameter <K extends Comparable<? super K>> of the type BST<K,V>

这是我在创建一个名为的抽象类BST<K extends Comparable<? super K>, V>然后拥有另一个扩展这个命名的类后得到的错误RectangleBST<K,V>。所以RectangleBST<K,V> extends BST<K,V>但是当我使用BST<K, V>.

一种解决方案是使用 extends BST<Integer, Rectangle>,但这是否意味着我现在已经继承了专门用于 Integer 类型的 Key 和 Rectangle 类型的 Value 的方法?

另一个可能是在 RectangleBST 中进行比较,尽管我相信我的计划是在 BST 而不是 RectangleBST 中比较键?

标签: javagenerics

解决方案


泛型类型参数不必命名相同,所以为了更好地看出区别,让我们重命名它们:

BST<A extends Comparable<? super A>, B>
RectangleBST<C, D> extends BST<C, D>

这类似于函数调用:

bst(int a, int b)
rectangleBst(int c, int d) {
    bst(c, d);
}

但是,它仅在c与 兼容时才有效a。我的意思是,如果CA.

它不是,因为C可以是任何类型,甚至是不实现/扩展的类型Comparable。由于A需要类型参数来实现/扩展ComparableC因此不兼容。

为了使其兼容,您还需要限制C实现/扩展的类型Comparable

RectangleBST<C extends Comparable<? super C>, D> extends BST<C, D>

现在C兼容A.


好的,现在使用您想要的名称:

BST<K extends Comparable<? super K>, V>
RectangleBST<K extends Comparable<? super K>, V> extends BST<K, V>

请记住,KinRectangleBST与in不同 。它是一个不同的映射到in ,与映射到相同。KKBSTKKBSTCA


推荐阅读