【问题标题】:extending a class where a parameter of the parent class extends a class扩展一个类,其中父类的参数扩展一个类
【发布时间】:2014-04-06 23:09:08
【问题描述】:

我正在尝试将 TreeMap 的一个版本扩展为子类以更有效地索引单词,但我不确定正确的语法是什么。树形图的类定义如下所示

public class MyTreeMap<K extends Comparable<? super K>,V> extends AbstractMap<K,V> {

以最直接的方式扩展类

public class TreeMapIndexer<K> extends MyTreeMap<K,LinkedList<Integer>> {

产生错误 “绑定不匹配:类型 K 不是 MyTreeMap 类型的有界参数 > 的有效替代品”。

我试过了

public class TreeMapIndexer<K> extends 
MyTreeMap<K extends Comparable<? super K>, LinkedList<Integer>> {

相反,但这会产生编译器错误“令牌“扩展”的语法错误,预期”。错误的扩展在“”中。

我发现另一个线程 (Generic Generics: "Syntax error on token "extends", , expected") 具有相同的错误消息。这似乎与我的情况略有不同,但我尝试了

public class TreeMapIndexer<K> extends 
MyTreeMap<K, K extends Comparable<? super K>, LinkedList<Integer>> {

这会产生完全相同的“令牌“扩展”,,预期的语法错误”编译器消息。

【问题讨论】:

    标签: java generics inheritance comparable


    【解决方案1】:
    class MyTreeMap<K extends Comparable<? super K>, V>
    extends AbstractMap<K, V>
    

    所以K 被声明为具有extends Comparable&lt;? super K&gt; 的边界。您只需要在子类上重新声明相同的界限。

    class TreeMapIndexer<K extends Comparable<? super K>>
    extends MyTreeMap<K, LinkedList<Integer>>
    

    否则,您试图将子类型声明为没有编译错误“绑定不匹配”的限制。

    您尝试的几乎是正确的,绑定只需要在泛型类型声明中,而不是参数(传递给超类)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-18
      • 2020-10-05
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      • 2019-08-31
      相关资源
      最近更新 更多