有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数据结构二进制搜索树泛型Java

我正在用java实现一个通用的BST。标准BST位于文件BST.java中。我还有一个子类,它添加了额外的功能。我似乎无法让泛型发挥作用。每次比较insert、get或delete时,我都会遇到以下错误:

compareTo(Key) in java.lang.Comparable<Key> cannot be applied to (java.lang.Comparable)
    int cmp = k.compareTo(n.k);

java

public class BST <Key extends Comparable<Key>, Value>
{
    //code here

    public Value Get (Key k)
    {
        Get(this.root, k);
    }

    private Value Get (Node n, Key k)
    {
        if (n == null || k == null) return null;
        int cmp = k.compareTo(n.k);
        if (k.compareTo(n.k) == 0) return (Value) n.v;
        if (cmp < 0) Get (n.left, k);
        if (cmp > 0) Get (n.right, k);
    }

    private class Node <Key extends Comparable<Key>, Value>
    { 
        public Key k;
        public Value v;
        public Node left;
        public Node right;

        //code here 
    }
}

扩展。爪哇

public class BSTExtended<Key extends Comparable<Key>, Value> extends BST<Key, Value>
{ //code here }

共 (1) 个答案

  1. # 1 楼答案

    我相信您的问题在于,在BST类的定义中的不同点上,您缺少对类型参数的显式引用。还有一些非常基本的编译器错误

    特别是,请查看Get函数的修改类型签名:

    private Value Get (Node<Key, Value> n, Key k)
    

    这是我上的全部课程:

    public class BST <Key extends Comparable<Key>, Value>
    {
        Node<Key, Value> root;
        //code here
    
        public Value Get (Key k)
        {
            return Get(this.root, k);
        }
    
    
        private Value Get (Node<Key, Value> n, Key k)
        {
            if (n == null || k == null) return null;
            int cmp = k.compareTo(n.k);
            if (k.compareTo(n.k) == 0) return (Value) n.v;
            if (cmp < 0) return Get (n.left, k);
            return Get (n.right, k);
        }
    
        private class Node <Key extends Comparable<Key>, Value>
        { 
            public Key k;
            public Value v;
            public Node<Key, Value> left;
            public Node<Key, Value> right;
    
            //code here 
        }
    }