我有一个非常基本的方法作为二叉搜索树的一部分,如果当前二进制节点有一个正确的子节点,它只返回True,如果右边的子节点指向null,则返回False.
public boolean hasRight(){ if(right.element != null){ return true; }else{ return false; }
但是每当我测试这段代码时,我知道我将到达一个没有正确子节点的节点,并且希望我的代码只返回False,那么java会在该行处抛出NullPointerException
if(right.element != null)
而不是像我期望的那样返回False.
编辑:
修复了我的代码,在尝试获取正确的元素之前,只需检查自己是否为null
public boolean hasRight(){ if(right != null){ return true; }else{ return false; } }右边本身就是空的.在尝试访问它之前先检查它.
if (right != null && right.element != null){
精彩评论