【问题标题】:Errors with generic class extending other generic class泛型类扩展其他泛型类的错误
【发布时间】:2014-09-22 14:53:15
【问题描述】:

我遇到了泛型类的问题,我将用我的示例类来解释它:

二叉树

public class BinaryTree<T extends Comparable<T>> {

索引

public abstract class Indexed<T extends Comparable<T>> implements Comparable<Indexed<T>> {

IndexedBinaryTree

public class IndexedBinaryTree<T extends Indexed<? extends Comparable<Indexed<?>>>> extends BinaryTree<T> {

扩展索引的示例类

public class Vokabel extends Indexed<String> {

IndexedBinaryTree 不工作。我想要做的是拥有一个包含索引对象的 BinaryTree,可以像这样创建:

IndexedBinaryTree<Vokabel> ibt = new IndexedBinaryTree<>();

错误 NetBeans 给了我:

类型参数? extends Comparable> 不在范围内 类型变量 T 其中 T 是一个类型变量: T 扩展了在 Indexed 类中声明的 Comparable

> expected

type argument T#1 is not within bounds of type-variable T#2
  where T#1, T#2 are type-variables:
    T#1 extends Indexed<? extends Comparable<Indexed<?>>> declared in class IndexedBinaryTree
    T#2 extends Comparable<T#2> declared in class BinaryTree

【问题讨论】:

  • “不工作”是什么意思?请详细说明。
  • 定义不起作用。发布错误以及预期的行为是什么。
  • 已编辑主帖(i.imgur.com/SRx0iDv.png - 错误截图)
  • 我不明白这个声明:Indexed&lt;T extends Comparable&lt;T&gt;&gt; implements Comparable&lt;Indexed&lt;T&gt;&gt;。强制 T 成为 Comparable 然后将 Comparable 强制在不同的东西上的目的是什么?
  • 您可能需要K extends Comparable&lt;K&gt;, T extends Indexed&lt;K&gt; 之类的内容。你对我上面的评论感到困惑。您似乎希望 T 成为 Indexed 并成为 Indexed 的类型参数。

标签: java generics


【解决方案1】:

这样编译:

class BinaryTree<T extends Comparable<? super T>> {}
abstract class Indexed<T extends Comparable<? super T>> implements Comparable<Indexed<T>> {}
class IndexedBinaryTree<T extends Indexed<?>> extends BinaryTree<T> {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多