如何使用Java的Comparable来比较树中的Generic对象?

时间:2013-04-23 04:35:48

标签: java comparable compareto

现在我正在尝试执行一项涉及创建可以接收任何通用对象的堆的赋值,并且节点可以通过实现Comparable接口进行相互比较。问题是,我找不到像这样比较通用对象的方法。

这是我目前为Node类所做的:

private class Node<E> implements Comparable<E>
{
    private E data;
    private Node left;
    private Node right;

    //constructors
    public Node(E data)
    {
        this.data = data;
        left = null;
        right = null;
    }

    public Node(E data, Node left, Node right)
    {
        this.data = data;
        this.left = left;
        this.right = right;
    }


   //returns current data
    public Object getData()
    {
        return this.data;
    }

    public int compareTo(E other)
    {
        return data.compareTo(other);
    }
}

当我尝试编译时,它说“找不到符号 - 方法比较(E)。”方法compareTo()在Comparable接口中,所以我无法理解为什么会发生这种情况,我不知道如何修复它。有人有任何想法吗?

2 个答案:

答案 0 :(得分:8)

您还需要将E定义为Comparable

private class Node<E extends Comparable<E>> implements Comparable<E>

此外,让Node类与自身相媲美可能更有意义:

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

答案 1 :(得分:0)

好的,你的代码还有以下几点:

// E needs to be restricted to the Comparable interface
// Also, You probably mean for Nodes to be comparable with each other
public class Node<E extends Comparable<E>> implements Comparable<Node<E>>
{
    private E data;
    // Remember to specify your generic parameter in references to Node as well!
    private Node<E> left;
    private Node<E> right;

    //constructors
    public Node(E data)
    {
        this.data = data;
        left = null;
        right = null;
    }

    public Node(E data, Node<E> left, Node<E> right)
    {
        this.data = data;
        this.left = left;
        this.right = right;
    }


    //returns current data
    // This should return your E generic type, not Object.
    public E getData()
    {
        return this.data;
    }

    // This now compares to a Node.
    public int compareTo(Node<E> other)
    {
        return data.compareTo(other.getData());
    }
}
相关问题