2

现在我正在尝试做一个涉及创建一个可以接收任何通用对象的堆的分配,并且节点可以通过实现 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);
    }
}

当我尝试编译时,它显示“找不到符号 - 方法 compareTo(E)”。compareTo() 方法在 Comparable 接口中,所以我不明白为什么会这样,也不知道如何解决。有人知道吗?

4

2 回答 2

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);
}
于 2013-04-23T04:47:29.720 回答
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());
    }
}
于 2013-04-23T04:50:40.320 回答