代码之家  ›  专栏  ›  技术社区  ›  ineedahero

无法比较可比较的类型(对象)

  •  -2
  • ineedahero  · 技术社区  · 6 年前

    参数类型的运算符>未定义 java.lang.com, java.lang.com

    搞什么鬼?

    (这是密码)

    public class BST<T extends Comparable<T>> {
        public static class Node<P extends Comparable<P>> {
            P val;
            Node<P> left;
            Node<P> right;
    
            public Node() {
    
            }
    
            public Node(P val) {
                this.val = val;
            }
        }
    
        Node<T> root;
    
        private void addValHelper(Node root, Node newNode) {
            if (root.val > newNode.val) { // <-- ERROR IS HERE
                if (root.left == null) {
                    root.left = newNode;
                } else {
                    addValHelper(root.left, newNode);
                }
            } else {
                if (root.right == null) {
                    root.right = newNode;
                } else {
                    addValHelper(root.right, newNode);
                }
            }
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  7
  •   Dan    6 年前

    Java没有操作符重载。你不能把可比较的类型和 > . 你需要使用 root.val.compareTo(newNode.val) 相反。

    作为旁白:

    • 您不需要指定 <P extends Comparable<P>>
    • 也许移动这个按钮更有意义 addValHelper
    • Node 实施 Comparable

    这样,您的代码感觉更加习惯化,并且您不会将节点的字段公开给BST。

    public class BST<T implements Comparable<T>> {
        private final Node<T> root;
    
        /** Presumably this is run when a value is added.. */
        private void addValueHelper(Node rootNode, Node newNode) {
            rootNode.attachChild(newNode);
        }
    
        public static class Node implements Comparable<T> {
            private final T val;
            private Node left;
            private Node right;
    
            public Node(T val) {
                this.val = val;
            }
    
            public int compareTo(Node other) {
                return this.val.compareTo(other.val);
            }
    
            /**
             * Takes the given node and compares it with the current node.
             * If the current node is greater than the given node, the given node is placed to the left.
             * Otherwise it is placed to the right.
             */
            protected void attachChild(Node newNode) {
                if (this.compareTo(newNode) == 1) {
                    if (this.left == null) {
                        this.left = newNode;
                        return;
                    }
                    this.left.attachChild(newNode);
                    return;
                } 
    
                if (this.right == null) {
                    this.right = newNode;
                    return;
                }
    
                this.right.attachChild(newNode);
            }
        }
    }