空指针异常,我想创建一个方法“headSet
”,创建并返回一个新的TreeSet
,set
,这是在叫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);
}
你是否得到NullPointerException? –
调试并查看实际为空?另外,实际的堆栈跟踪可能会有所帮助。 – Taylor
也许你在最后一个节点,没有比它大的东西。检查你的headSet中的n.right!= null(n.right,before,set) – Keerthivasan