Java比较泛型类型
在Java中,我编写了一个Binary Search Tree类,该类使用递归添加节点。现在,我想使用泛型对其进行概括,以便我可以了解更多有关它们的信息。
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未定义”。
在寻找解决方案时,一个答案是比较通用类型Java:
class Element<T extends Comparable<T>>我不知道这应该去哪里,以及与实现Comparable的类有何不同。我知道类型的唯一位置在主类中,所以compareTo()应该在那里吗?我曾考虑过将GBinTree设置为接口,但感到困惑,是否正确?任何帮助,将不胜感激。
回答:
您不能在Java中重载运算符。该<运算符仅适用于原始(或数字)类型,不适用于引用类型。由于T是代表引用类型的类型变量,因此不能<在type变量上使用T。你必须用
if (item.compareTo(bn.item) < 0)检查返回的值并决定使用它做您想做的事情。
您不知道类型T是什么,但是您知道它将是实现Comparable并因此实现compareTo()方法的类型。
以上是 Java比较泛型类型 的全部内容, 来源链接: utcz.com/qa/407893.html








