【发布时间】:2011-04-13 13:39:08
【问题描述】:
我一直在使用驱动程序来测试我的一种数据结构(二叉搜索树) 我遇到了这个问题。 - 当我在 bst 中插入超过 2 个对象时会发生这种情况 - 我正在尝试做什么:我将 4 个对象插入树中,然后我删除 2 个对象,然后打印出我的 find 方法,以便它显示是否找到了我请求的对象。 例如:
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));
我在运行时收到此错误:
线程“main”java.lang.ClassCastException 中的异常:TreeNode 无法转换为 java.lang.Comparable 在 BinarySearchTree2.delete(BinarySearchTree2.java:83) 在 Driver5.main(Driver5.java:36)
然后指向我的 bst 类中的删除方法:
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));
}
}
错误直接指向我的删除方法中的这一行:
nd.setItem((E)nd.getRight());
【问题讨论】:
标签: java exception class casting binary-search-tree