java - 泛型和通配符
问题描述
我正在设计一个 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 中比较键?
解决方案
泛型类型参数不必命名相同,所以为了更好地看出区别,让我们重命名它们:
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
。我的意思是,如果C
与A
.
它不是,因为C
可以是任何类型,甚至是不实现/扩展的类型Comparable
。由于A
需要类型参数来实现/扩展Comparable
,C
因此不兼容。
为了使其兼容,您还需要限制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>
请记住,K
inRectangleBST
与in不同 。它是一个不同的映射到in ,与映射到相同。K
K
BST
K
K
BST
C
A
推荐阅读
- haproxy - 'option accept-invalid-http-response' 在 HAProxy 1.7.12 中是否有效?
- python - 如何为每种类型创建四分位数折线图
- c# - 使用 WinExe 发布 wpf 应用程序仍然打开控制台主机窗口
- reactjs - 当我在引导程序中使用它时,多项目轮播不起作用
- java - org.springframework.web.client.ResourceAccessException:“https://[myendpoint]”的 GET 请求出现 I/O 错误
- reactjs - 使用带有 redux 状态的材料表
- javascript - 从 REST API 返回数组中的前 2 个 json 名称/值对
- sql-server - 使用 CTE 和交叉连接的 t-sql 长查询
- r - 在 dplyr 的列中添加噪声
- asp.net-core - Azure AD 身份验证重定向不到本地主机