Ben
Ben

Reputation: 21625

Java's compareTo method - cannot find symbol error

Java beginner here trying to implement an AVL tree but I'm getting hung up trying to get the compareTo() method to work.

public class AVLTree<AnyType extends Comparable<? super AnyType>>
{

    //Constructor
    AVLTree()
    {
        root = null;
    }

    public void SanityCheck()
    {
        System.out.println("Hello World");
    }

    public void Insert(AnyType x, AVLNode<AnyType> insertAtNode)
    {

        //if starting node is null, it is the root.
        if(insertAtNode == null){
            if(root == null){
                root = new AVLNode(x);
            } else{
                Insert(x, root);
            }
        } else{
            if(compareTo(insertAtNode.element, x) > 0){ //Bias here.  Fix later
                if(insertAtNode.rightChild == null){
                    AVLNode newNode = new AVLNode(x);
                    insertAtNode.rightChild = newNode; //Actual insertion happens here
                } else {
                    Insert(x, insertAtNode.rightChild);
                }
            } else{
                if(insertAtNode.leftChild == null){
                    AVLNode newNode = new AVLNode(x);
                    insertAtNode.leftChild = newNode; //Actual insertion happens here
                } else{
                    Insert(x, insertAtNode.leftChild);
                }
            }
        }
    }

    private class AVLNode<AnyType extends Comparable<? super AnyType>>
    {
    //Constructor
        AVLNode(AnyType theElement)
        {
            element = theElement;
        }

        AnyType element;
        AVLNode<AnyType> leftChild;
        AVLNode<AnyType> rightChild;
    }

    AVLNode root;
}

Ignore the algorithm - it's obviously unfinished. But why do I keep getting the "cannot find symbol: compareTo" when I try to compile?

Upvotes: 0

Views: 2288

Answers (1)

August
August

Reputation: 12558

You don't have a method named compareTo in the current class.

You probably meant to call the compareTo method of insertAtNode.element:

if (insertAtNode.element.compareTo(x) > 0) {
    ...
}

Another thing to note is that by Java convention, method names are camelCase. For example, SanityCheck should be sanityCheck.

Upvotes: 2

Related Questions