[英]Null Pointer Exception in Recursive method
我正在尝试创建一个方法' headSet
',该方法创建并返回一个新的TreeSet
set
值,这些值都是被调用TreeSet
中所有小于参数元素'before'的值。
我可以得到所有正确的遍历,并且在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;
}
其中root是被调用的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);
}
}
第二个递归函数不进行比较,只是将所有节点分支添加到新的Sorted Tree 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);
}
首先,我认为您不会通过SortedSet实现您计划的目标。 因为当您将对象添加到SortedSet时,它会根据要添加到该对象的对象定义的compareTo方法对对象的内部顺序进行排序。 现在,在您的情况下,最简单的方法是实现Comparable to n.data类。 这样做时,可以使用myCompare方法中定义的逻辑。 现在以任意顺序将n.data添加到SortedSet中,SortedSet将使用其自然顺序来组织它们。 如果您真的想以编程方式维护订单,请使用列表。 现在让我们说您摆脱了NPE,然后要打印存储在Set中的n.data并想验证您的排序算法是否起作用,您无法执行此操作,因为set会根据其自然返回对象列表排序顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.