【问题标题】:Java Generics in a Binary Tree, incompatible types error二叉树中的Java泛型,类型不兼容错误
【发布时间】:2015-10-17 14:32:06
【问题描述】:

我正在尝试使用泛型在 java 中实现二叉树,我搜索并找到了这个问题:Implementing Binary Tree in Java with Generic Comparable<T> data?,但我无法解决我的疑问。所以我有两个班,

BST_Tree<T> 

Node<T extends Comparable<T>> 

我希望我的实现可以:

  1. 将每种类型的Object放入Node中的key字段中

  2. 将每个节点与key 字段进行比较

这是代码:

public class Node < T extends Comparable < T >> {

    private T key;
    private Node left;
    private Node right;
    private Node p;

    public void setKey(T key) {
        this.key = key;
    }

    public T getKey() {
        return key;
    }

    public Node getLeft() {
        return left;
    }

    public Node getRight() {
        return right;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    public void setP(Node p) {
        this.p = p;
    }

    public boolean getBolCompMin(T key) {
        return this.key.compareTo(key) < 0;
    }
}

我的 Node 类应该扩展 Comparable 以便比较密钥。

这是我的树:

public class BST_Tree < T > {

    private ArrayList < Node > nodes;
    private Node root;

    public BST_Tree(Node root) {
        this.root = root;
    }

    public void insertNode(T key) {
        Node z = new Node();
        z.setKey(key);
        Node x = this.root;
        Node y = new Node();

        while (x != null) {

            y = x;
            if (z.getBolCompMin(x.getKey())) {
                x = x.getLeft();
            } else {
                x = x.getRight();
            }
        }

        z.setP(y);

        if (z.getBolCompMin(y.getKey())) {
            y.setLeft(z);
        } else {

            y.setRight(z);
        }
    }
    public void InOderWalk(Node x) {
        if (x != null) {
            InOderWalk(x.getLeft());
            System.out.println(x.getKey());
            InOderWalk(x.getRight());
        }
    }

    public Node getRoot() {
        return root;
    }
}

我的树尝试在节点 z 中设置键,但失败了。这是错误:

不兼容的类型:T 无法转换为 java.lang.Comparable

提前谢谢你!

【问题讨论】:

  • BST_Tree = BinarySearchTree_Tree
  • 为了获得最佳效果,请使用&lt;T extends Comparable&lt;? super T&gt;&gt;
  • 我能问你为什么吗?顺便谢谢你

标签: java generics tree


【解决方案1】:

你的

public class BST_Tree<T>

应该是

public class BST_Tree<T extends Comparable<T>>

BST_TreeNode 类中的每个 Node 变量都应该是 Node&lt;T&gt;

这将确保您只能使用实现 Comparable 的元素类型来实例化您的 BST_Tree 类。

【讨论】:

  • Node 中的 getBolCompMin(T key) 方法怎么样,当然,只有在 Node 扩展具有可比性时才能工作。顺便说一句,如果一个键是当前节点的键(this.key)的次要,则该方法返回true
  • @Francesco 我仍然不明白你在评论中问了什么。 getBolCompMin 对我来说很好。
  • 好的,它只有在 Node 扩展 Comparable 时才能工作,因为它使用了 Comparable (.compareTo) 中的方法
  • @Francesco 你的意思是它只有在T 实现Comparable&lt;T&gt; 时才能工作,它确实做到了。
  • 所以你的意思是我的班级必须实现 Comparable
猜你喜欢
  • 2011-04-18
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多