【问题标题】:comparing generic type E node objects比较泛型 E 型节点对象
【发布时间】:2014-10-18 15:25:39
【问题描述】:

我有课

private class BSTNode<E extends Comparable<E>> implements Comparable<E> {
    BSTNode<E> left, right;
    E data;

带有构造函数和compairTo方法

但是当我想实例化 BSTNode 类时,我遇到了问题。

public class BST {
private BSTNode<E> root;

/* Constructor */
public BST() {
    root = new BSTNode<E>();
}

我应该如何在我的 BST 类中使用 BSTNode?谢谢

【问题讨论】:

  • 它首先建议将 E 类型参数添加到 BST --> BST 并且当我这样做时它说:绑定不匹配:类型 E 不是有界参数的有效替代品 .BSTNode 类型的 Comparable>
  • 您需要指定 E,即说一个实现可比较的 MyClass,否则也使 BST 通用。
  • @almasshaikh 是的,我也想让 BST 通用,但是如何?

标签: java generics binary-search-tree comparable


【解决方案1】:

这些方面的东西(不是完整的或具体的):

public class BST<E extends Comparable<E>> 
{
  private class BSTNode<E extends Comparable<E>> implements Comparable<E> {
  BSTNode<E> left, right;
  E data;
  @Override
  public int compareTo(E o) {
    return 0;//implement method here
  }
 }
 private BSTNode<E> root;
 public BST() {
   root = new BSTNode<E>();//while comparing you would need to case E to comparable and call compareTo method
 }

 public static void main(String[] args) 
 {
    BST<String> messages = new BST<String>();
 }
}

【讨论】:

  • 至少错误消失了,我稍后会测试正确性。谢谢
【解决方案2】:

您的类标头意味着您的 BTSNode 只能使用实现 Comparable 接口的类 E 实例化。

因此,您应该可以按如下方式使用它:

public class BST {
    private BSTNode<Integer> root;

    /* Constructor */
    public BST() {
        root = new BSTNode<Integer>();
    }
}

Integer 可以替换为here 列出的任何其他实现类,甚至是您自己的自定义实现。

【讨论】:

    猜你喜欢
    • 2012-05-11
    • 2014-12-10
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2014-06-13
    相关资源
    最近更新 更多