【问题标题】:Implementing Comparable for a Node in Java在 Java 中为节点实现 Comparable
【发布时间】:2016-01-01 11:01:15
【问题描述】:

我是 Java 新手,因此这些问题对某些人来说可能看起来微不足道。 我有一个 Node 类的实现,它使用通用数据类型 T。我想实现一个可比较的来比较 T 的两个实例。

这是我的代码。

private class Node<T> implements Comparable<T> {
        private T data;
        private Node next;

        public Node(T data){
            this.data = data;
            this.next = null;
        }

        @Override
        public int compareTo(T other) {
            if(this.data == other) return 0;
            if(this.data < other) return 1;
            if(this.data > other) return -1;
        }
    }

此代码无法编译,因为 Java 会抛出错误的操作数类型错误。编写 compareTo 函数的正确方法是什么。任何帮助表示赞赏。

【问题讨论】:

    标签: java comparable


    【解决方案1】:

    首先,您需要 Ts 在它们之间具有可比性。你想要的基本上只是

    private class Node<T extends Comparable<T>> implements Comparable<Node<T>> {
        ...
    
        @Override
        public int compareTo(Node<T> other) {
           return data.compareTo(other.data);
        }
    }
    

    【讨论】:

    • 如果我只想比较两个 T 值而不是两个节点,那么如何实现可比较。
    • 什么意思,比较两个T 值?如果您有两个 T 值,只需调用 t1.compareTo(t2)
    • 我正在尝试这样做。 private class Node&lt;T extends Comparable&lt;T&gt;&gt; { private T data; private Node next; public Node(T data){ this.data = data; this.next = null; } public int compareTo(T other){ return data.compareTo(other); } }
    • 我在堆栈的实现中使用了这个节点。所以后来当我打电话给if(((Comparable) item).compareTo(minValue)){ //do something } 我得到一个编译错误
    • 其实想通了。谢谢。
    猜你喜欢
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 2014-07-05
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多