【问题标题】:Java comparing generic typesJava比较泛型类型
【发布时间】: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 成为一个界面,但对这是否是正确的轨道感到困惑?任何帮助将不胜感激。

【问题讨论】:

  • 为了获得最佳效果,请使用&lt;T extends Comparable&lt;? super T&gt;&gt;
  • 请查看this post希望它符合您的期望。

标签: java generics


【解决方案1】:

您不能在 Java 中重载运算符。 &lt; 运算符仅适用于原始(或数字)类型,不适用于引用类型。由于T 是表示引用类型的类型变量,因此您不能对T 类型的变量使用&lt;。你必须使用

if (item.compareTo(bn.item) < 0) 

检查返回的值并决定用它做什么。

您不知道T 是什么类型,但您知道它将是实现Comparable 并因此实现compareTo() 方法的类型。

【讨论】:

  • 为了 OP 的利益,最后一段的旁注:基本上,作为实现 GBinNode&lt;T extends Comparable&lt;T&gt;&gt; 的人,您不负责实现 compareTo,这是使用您的代码的人的工作,以确保无论T 是,它已经实现了该方法。否则,代码甚至无法编译。
【解决方案2】:

您可以使用这种简单的方法
对于大于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)
    ...
}

【讨论】:

    【解决方案3】:

    在编写通用排序时遇到了这个问题。我想出的最佳解决方案是在排序函数的参数中添加一个比较器并使用比较方法。在创建 new Comparator&lt;T&gt;()T 以替换为所需类型时,您必须在函数调用时/之前覆盖 compare(T o1,To2) 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 2012-11-16
      • 2010-12-29
      相关资源
      最近更新 更多