Java比较泛型类型

Java比较泛型类型,java,generics,Java,Generics,在Java中,我编写了一个二进制搜索树类,它使用递归添加节点。现在我想用泛型来概括它,这样我可以了解更多关于它们的知识 public class GBinNode<T> { T item; GBinNode<T> left; GBinNode<T> right; public GBinNode(T newItem) { item = newItem; left = null; right = null;

在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()+" ";
    }
}
公共类GBinNode{
T项;
GBinNode左;
GBinNode权利;
公共GBinNode(新项目){
项目=新项目;
左=空;
右=空;
}
公共GBinNode(T it、GBinNode le、GBinNode ri){
项目=it;
左=左;
右=ri;
}
公共字符串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{
GBinNode增补(T项,GBinNode bn){
如果(bn==null){
返回新的GBinNode(项,空,空);
}
如果(item
主类有以下代码来启动它。我使用字符串,但数据类型可能是一些复杂类型

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);
gbintreebt=newgbintree();
GBinNode root=null;
根=bt.add(“Calex”,根);
root=bt.add(“Ealex”,root);
根=bt.add(“Balex”,根);
root=bt.add(“Dalex”,root);
bt.toString(根);
我开始使用Comparable接口,但接下来如何编写CompareTo()函数?我不知道t将是什么类型?我得到的错误是“参数类型t,t的运算符<未定义”

在寻找解决方案时,一个答案是:

类元素

我不明白这个应该放在哪里,以及它与实现Comparable的类有什么不同。我只知道该类型在主类中,compareTo()也应该在主类中有吗?我想让GBinTree成为一个接口,但我不知道这是否正确?如果有任何帮助,我们将不胜感激。

您不能在Java中重载运算符。
您可以使用这种简单的方法
对于大于root.getData=1的数据,对于等于root.getData=0的数据,对于小于root.getData=-1的数据

public class BST<E extends Number & Comparable<? super E>>{
    void add(){
    ...
    if(data.compareTo(root.getData()) == 1)
    ...
}

public class BSTA为OP的利益在最后一段附加说明:基本上,作为实现
GBinNode
的人,您不负责实现compareTo,使用您的代码的人的职责是确保无论
T
是什么,它都已经实现了该方法。否则,代码甚至不会执行mpile.为了获得最佳效果,请使用
检查,我希望它符合您的期望。
if (item.compareTo(bn.item) < 0) 
public class BST<E extends Number & Comparable<? super E>>{
    void add(){
    ...
    if(data.compareTo(root.getData()) == 1)
    ...
}