2

Right now I'm trying to do an assignment involving creating a heap that can receive any generic object, and the nodes can compare each other by implementing the Comparable interface. Problem is, I can't find a way to compare generic object like this.

This is what I have so far for the Node class:

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);
    }
}

When I try to compile, it says "Cannot find symbol -- Method compareTo(E)." The method compareTo() is in the Comparable interface, so I can't understand why this is happening, and I don't know how to fix it. Anyone have any idea?

user2309750
  • 1,403
  • 4
  • 14
  • 11

2 Answers2

8

You need to define E as Comparable as well:

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

Also, it would probably make more sense to have your Node class comparable to itself:

private class Node<E extends Comparable<E>> implements Comparable<Node<E>>
...
public int compareTo(Node<E> other)
{
    return data.compareTo(other.data);
}
SimonC
  • 6,590
  • 1
  • 23
  • 40
0

Okay, so a couple of things with your code:

// 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());
    }
}
Julien Langlois
  • 482
  • 3
  • 11