Scott Rogener
Scott Rogener

Reputation: 31

using compareTo in Binary Search Tree program

I've been working on this program for a few days now and I've implemented a few of the primary methods in my BinarySearchTree class such as insert and delete. Insert seemed to be working fine, but once I try to delete I kept getting errors. So after playing around with the code I wanted to test my compareTo methods. I created two new nodes and tried to compare them and I get this error:

Exception in thread "main" java.lang.ClassCastException: TreeNode cannot be cast to java.lang.Integer at java.lang.Integer.compareTo(Unknown Source) at TreeNode.compareTo(TreeNode.java:16) at BinarySearchTree.myComparision(BinarySearchTree.java:177) at main.main(main.java:14)

Here is my class for creating the nodes:

    public class TreeNode<T> implements Comparable
    {
        protected TreeNode<T> left, right;
        protected Object element;

    public TreeNode(Object obj)
    {
        element=obj;
        left=null;
        right=null;
    }

   public int compareTo(Object node)
   {
       return ((Comparable) this.element).compareTo(node);
   }

}

Am I doing the compareTo method all wrong? I would like to create trees that can handle integers and strings (seperatly of course)

Upvotes: 3

Views: 7607

Answers (3)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

To be sure that the element indeed is a comparable object, and avoid all the casts, you could do something like this:

public class TreeNode<T extends Comparable<? super T>>
implements Comparable<TreeNode<T>> {

    protected TreeNode<T> left, right;
    protected T element;

    public TreeNode(T obj) {
        element = obj;
        left = null;
        right = null;
    }

    @Override
    public int compareTo(TreeNode<T> node) {
        return element.compareTo(node.element);
    }

}

For an usage example:

TreeNode<Integer> node1 = new TreeNode<Integer>(2);
TreeNode<Integer> node2 = new TreeNode<Integer>(3);
System.out.println(node1.compareTo(node2));

The above snippet prints -1 on the console.

Upvotes: 4

Brett Walker
Brett Walker

Reputation: 3576

Try

public <T> int compareTo(Object node) 
{ 
    return ((Comparable) this.element).compareTo( ( TreeNode<T> ) node ).element); 
} 

Upvotes: 2

LeleDumbo
LeleDumbo

Reputation: 9340

compareTo method is applied against TreeNode (passed as node parameter), while you compare it with this.element, which is an Object contained in the TreeNode. Simply change to:

return ((Comparable) this.element).compareTo(node.getElement());

assuming you have getElement method.

Upvotes: 2

Related Questions