using compareTo in Binary Search Tree program
Posted
by
Scott Rogener
on Stack Overflow
See other posts from Stack Overflow
or by Scott Rogener
Published on 2011-11-21T01:46:28Z
Indexed on
2011/11/21
1:50 UTC
Read the original article
Hit count: 309
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)
© Stack Overflow or respective owner