【发布时间】: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<Integer> tree = new BinarySearchTree<>();
【问题讨论】:
-
为什么要将字符串添加到
BinarySearchTree<Integer>? -
那是一个我还没有修复的错误,我之前使用过字符串树。
-
自己做了一个最小的例子,它编译没有任何问题。如果您确实定义了自己的
Comparable,那么这确实是问题所在 -Integeris-ajava.lang.Comparable<Integer>,但您似乎希望它是您自己的Comparable类型,但事实并非如此.如果 Java 支持鸭子类型,它会是这样,但它不支持。
标签: java generics binary-search-tree