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

问题描述 投票:-2回答:1

我收到了这个神秘的错误:

对于参数类型java.lang.Comparable,java.lang.Comparable,未定义operator>

有没有搞错?

(这是代码)

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);
            }
        }
    }
}
java generics comparable
1个回答
7
投票

Java没有运算符重载。您无法将可比较类型与>进行比较。你需要使用root.val.compareTo(newNode.val)代替。

作为旁白:

  • 可比较是一个接口,而不是一个类
  • 您无需指定<P extends Comparable<P>>
  • addValHelper代码移动到Node类本身可能更有意义
  • Node实施Comparable可能有意义。

这样,您的代码感觉更加惯用,并且您不会将Node字段暴露给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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.