3

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)

Óscar López
  • 232,561
  • 37
  • 312
  • 386
Scott Rogener
  • 31
  • 1
  • 2
  • Thanks for all help guys! I ended up getting it working, but the problems was that I miswrote the variables a bit so I ended up confusing myself. The object I was passing to the compareTo method was the element itself, not a TreeNode. In my other class I kept passing it a TreeNode and thats why it was messing up. Thanks again. – Scott Rogener Nov 21 '11 at 07:30

3 Answers3

4

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
2

Try

public <T> int compareTo(Object node) 
{ 
    return ((Comparable) this.element).compareTo( ( TreeNode<T> ) node ).element); 
} 
Brett Walker
  • 3,566
  • 1
  • 18
  • 36
2

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.

LeleDumbo
  • 9,192
  • 4
  • 24
  • 38