【发布时间】:2013-12-27 00:24:30
【问题描述】:
在 Java 中,我编写了一个使用递归添加节点的二叉搜索树类。现在我想使用泛型对其进行概括,以便了解更多关于它们的信息。
public class GBinNode<T> {
T item;
GBinNode<T> left;
GBinNode<T> right;
public GBinNode(T newItem) {
item = newItem;
left = null;
right = null;
}
public GBinNode(T it, GBinNode<T> le, GBinNode<T> ri) {
item = it;
left = le;
right = ri;
}
public String toString() {
return item.toString()+" ";
}
}
我添加节点的函数在下面的类中
public class GBinTree<T extends Comparable <T>> {
GBinNode<T> add(T item, GBinNode<T> bn) {
if (bn==null) {
return new GBinNode<T>(item, null, null);
}
if (item < bn.item) { // ERROR HERE
bn.left = add( item, bn.left);
}
else {
bn.right = add( item, bn.right);
}
return bn;
}
public void toString(GBinNode<T> root) {
GBinNode<T> curr = root;
if (curr == null)
return;
else {
toString(curr.left);
System.out.println(curr.toString()); // inorder traversal
toString(curr.right);
}
}
主类有以下代码来启动。我使用的是字符串,但数据类型可能是一些复杂的类型。
GBinTree<String> bt = new GBinTree<String>();
GBinNode<String> root = null;
root = bt.add("Calex", root);
root = bt.add("Ealex", root);
root = bt.add("Balex", root);
root = bt.add("Dalex", root);
bt.toString(root);
我开始使用 Comparable 接口,但是如何编写 CompareTo() 函数?不知道T会是什么类型?我得到的错误是“参数类型 T、T 的运算符
正在寻找解决方案,一个答案是Comparing generic types Java:
class Element<T extends Comparable<T>>
我不明白这应该去哪里,以及它与实现 Comparable 的类有何不同。我知道类型的唯一地方是在主类中,那么 compareTo() 应该在那里吗?我看着让 GBinTree 成为一个界面,但对这是否是正确的轨道感到困惑?任何帮助将不胜感激。
【问题讨论】:
-
为了获得最佳效果,请使用
<T extends Comparable<? super T>> -
请查看this post希望它符合您的期望。