【问题标题】:Error java.lang.Integer is not within bounds of type-variable T; BinarySearchTree错误 java.lang.Integer 不在类型变量 T 的范围内;二叉搜索树
【发布时间】:2017-05-25 09:35:36
【问题描述】:

我想创建一个简单的二叉搜索树,它使用泛型来指定数据类型。 但是,当我想创建一个新的整数树时,我收到以下错误:

类型参数 java.lang.Integer 不在类型变量 T 的范围内

我尝试了其他明显扩展 Comparable 的数据类型,为什么这不起作用?

这是我的代码:

界面:

public interface Comparable<T>
{
    int compareTo( T t );
}

二叉搜索树:

public class BinarySearchTree<T extends Comparable<T>>
{
private T content;
private BinarySearchTree<T> leftChild, rightChild;

public BinarySearchTree()
{
    content = null;
    leftChild = null;
    rightChild = null;
}

public T getContent()     
{
    if(!isEmpty())
    {
        return content;
    }
    else
    {
        throw new RuntimeException();
    }
}

public boolean isEmpty()
{
    return content == null;
}

public boolean isLeaf()
{
    return !isEmpty() && leftChild.isEmpty() && rightChild.isEmpty();
}

public void add(T t)
{
    if(isEmpty())
    {
        content = t;
        leftChild = new BinarySearchTree<T>();
        rightChild = new BinarySearchTree<T>();
    }
    else
    {
        if(content.compareTo(t) > 0)
        {
            leftChild.add(t);
        }
        if(content.compareTo(t) < 0)
        {
            rightChild.add(t);
        }
    }
} 

public int size()
{
    if(isEmpty())
    {
        return 0;
    }
    else
    {
        return 1 + leftChild.size() + rightChild.size();
    }
}

public boolean contains(T t)
{
    if(isEmpty())
    {
        return false;
    }
    else
    {
        if(content.compareTo(t) > 0)
            leftChild.contains(t);
        else if(content.compareTo(t) < 0)
            rightChild.contains(t);
        return true;
    }
}

public void show()
{
    if(!isEmpty())
    {
        leftChild.show();
        System.out.println(content);
        rightChild.show();
    }
}

}

主要:

public class main
{

public static void main(String[] args)
{
    test();
}

public static void test()
{
    BinarySearchTree<Integer> tree = new BinarySearchTree<>();
    tree.add("5");
    tree.add("10");
    tree.add("3");
    tree.add("1");
    tree.show();
}
}

此行出现错误:BinarySearchTree&lt;Integer&gt; tree = new BinarySearchTree&lt;&gt;();

【问题讨论】:

  • 为什么要将字符串添加到BinarySearchTree&lt;Integer&gt;
  • 那是一个我还没有修复的错误,我之前使用过字符串树。
  • 自己做了一个最小的例子,它编译没有任何问题。如果您确实定义了自己的Comparable,那么这确实是问题所在 - Integer is-a java.lang.Comparable&lt;Integer&gt;,但您似乎希望它是您自己的Comparable 类型,但事实并非如此.如果 Java 支持鸭子类型,它会是这样,但它不支持。

标签: java generics binary-search-tree


【解决方案1】:

发生这种情况是因为您定义了自己的接口Comparable&lt;T&gt;,其中Integer 不是子类型。

删除您的Comparable,并改用java.lang 中的那个。

此外,正如 Eran 所指出的,您不应该将 String 值添加到 BinarySearchTree&lt;Integer&gt;

【讨论】:

  • 谢谢!那么,我自己的界面覆盖了默认界面,这是造成错误的原因吗?
  • 是的。创建自己的类或接口与java.lang 中的类或接口同名通常是一个坏主意。
【解决方案2】:

您不应该创建自己的Comparable 接口。它是JDK的一部分,你可以使用它。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多