【发布时间】:2013-10-22 11:02:50
【问题描述】:
我正在尝试创建一个方法'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);
}
}
第二个递归函数不进行比较,它只是将所有节点分支添加到新的排序树集'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 吗?
-
调试看看什么是空的?此外,实际的堆栈跟踪可能会有所帮助。
-
可能你在最后一个节点,没有比它更大的了。检查 headSet(n.right,before,set) 中的 n.right!=null
-
虽然不会触发 NPE。只有当 n 为空时 headSet(n.right,before,set) 才会触发 NPE
标签: java recursion nullpointerexception treeset