2013-10-22 49 views
0

空指针异常,我想创建一个方法“headSet”,创建并返回一个新的TreeSetset,这是在叫TreeSet这小于“前”参数元素的所有值的值。在递归方法

我可以得到所有正确的遍历,并且我在Net Beans中进行了调试,新集合确实包含它应该引发异常之前的所有值。我只是想不通为什么当我打电话headSet(n.right,before,set) ..特别是n.right ..它打破了。如果没有中断,它会工作得很好。

编辑:当我有问题的线路,headSet(n.right,before,set),运行该程序,那么所有3 headSet()方法调用主递归帮手是在堆栈跟踪。当我注释掉这一行时,除了错误的树遍历之外,没有任何问题。

这是被调用方法的主要公共触发递归助手:

public SortedSet<E> headSet(E before){ 
    SortedSet<E> set = new SearchTreeSet<E>(); 
    headSet(root, before, set); 
    return set; 
} 

其中根是在被叫TreeSet第一节点。

主要递归帮手:

private void headSet(Node n, E before, SortedSet<E> set) { 
    int comp = myCompare(n.data, before); 

    if (comp < 0){ //n.data is less than before 
    // add node n to the new set 
    if (n.data != null) { //It shouldn't be null but I just wanted to eliminate NPE sources 
     set.add(n.data); 
    } 
    // all nodes to the left are added automatically with a separate recursive function 
    headSet(n.left, set); 

    // test nodes to the right 

    //////////////The next statement forces a null pointer exception //////// 
    headSet(n.right, before, set); 
    } 
    // n.data is greater than or equal to 'before' 
    else { 

     // move to the left and retest 
     headSet(n.left, before, set); 
    } 
} 

第二递归函数不比较,它只是将所有节点跳转到新的排序树集合“设置”

private void headSet(Node n, SortedSet<E> set){ 
    if (n.data != null){ // 'if statement' is to eliminate NPE sources, it normally shouldn't be null 
    set.add(n.data); 
    } 
    if (n.left != null) { headSet(n.left, set); } 
    if (n.right != null) { headSet(n.right, set); } 
} 

解决 : 谢谢你们!那是它..我不相信我没有看到它。

这是我改变来解决这个问题:

if (n.left != null) { 
    headSet(n.left, set); 
} 

if (n.right != null) { 
    headSet(n.right, before, set); 
} 

而且还

if (n.right != null) { 
    headSet(n.right, before, set); 
} 
+0

你是否得到NullPointerException? –

+0

调试并查看实际为空?另外,实际的堆栈跟踪可能会有所帮助。 – Taylor

+0

也许你在最后一个节点,没有比它大的东西。检查你的headSet中的n.right!= null(n.right,before,set) – Keerthivasan

回答

0

首先,我不认为你会实现你与SortedSet的计划什么。 因为当您将对象添加到SortedSet时,它会根据您要添加到其中的对象定义的compareTo方法对对象的内部顺序进行排序。现在在你的情况下,最简单的事情就是实现Comparable到n.data类。当你这样做时,你可以使用你在myCompare方法中定义的逻辑。现在按任意顺序将n.data添加到SortedSet中,SortedSet将使用其自然顺序对它们进行组织。如果您确实想要以编程方式维护订单,请使用List。现在让我们说你摆脱了NPE,然后你想打印保存在Set中的n.data,并且想验证你的排序算法是否有效,你不能这么做,因为set会根据它的自然返回对象列表排序顺序。