簡體   English   中英

二進制搜索樹泛型Java

[英]Binary Search Tree Generics Java

我在java中實現了一個通用的BST。 標准BST位於文件BST.java中。 我還有一個子類,它添加了其他功能。 我似乎無法使泛型工作。 每次比較插入,獲取或刪除時,我都會收到以下錯誤:

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

BST.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 
    }
}

BSTExtended.java

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

我相信您的問題是您在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 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM