Reputation: 3
I have been using a driver to test one of my data structures(Binary Search Tree) and I have come across this issue. -It happens when I insert more than 2 objects into the bst -What I am trying to do: I am inserting 4 objects into the tree, then I am deleting 2 objects, and then printing out my find method so that it displays whether or not it found the objects I request. for instance:
BinarySearchTree2<Integer> theData1 = new BinarySearchTree2<Integer>();
long start1 = System.currentTimeMillis();
theData1.insert(c1);
theData1.insert(c2);
theData1.insert(c3);
theData1.delete(c2);
System.out.println(theData1.find(c1));
System.out.println(theData1.find(c2));
System.out.println(theData1.find(c3));
System.out.println(theData1.find(c4));
I receive this error when i run it:
Exception in thread "main" java.lang.ClassCastException: TreeNode cannot be cast to java.lang.Comparable at BinarySearchTree2.delete(BinarySearchTree2.java:83) at Driver5.main(Driver5.java:36)
which then points to the delete method in my bst class which is:
public void delete(E item) {
TreeNode<E> nd = root;
while(nd != null && nd.getItem().compareTo(item) != 0)
{
if(nd.getItem().compareTo(item) < 0)
nd = nd.getRight();
else
nd = nd.getLeft();
}
if( nd.getLeft() == null && nd.getRight() == null)
{
nd = null;
}
else if(nd.getLeft() != null && nd.getRight() == null)
{
nd.setItem((E)nd.getLeft());
}
else if(nd.getLeft() == null && nd.getRight() != null)
{
nd.setItem((E)nd.getRight());
}
else if(nd.getLeft() != null && nd.getRight() != null)
{
nd.setItem((E)findsucc(nd));
}
}
the error points directly to this line in my delete method:
nd.setItem((E)nd.getRight());
Upvotes: 0
Views: 4386
Reputation: 2301
I guess your declaration of E is "E extends Comaprable", in that case when you called nd.getRight
it returned TreeNode instance which has to be comparable for the cast to succeed.
The line where the exception occured should look like below for the cast to pass
nd.setItem(nd.getRight.getItem)
Upvotes: 2