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

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 に答える