二进制搜索树中的NullPointerException警告

时间:2019-07-08 00:12:42

标签: java data-structures binary-search-tree

 public void dfs(){
        LinkedList<BinaryNode> linkedList = new LinkedList<>();
        linkedList.add(root);

        while(!linkedList.isEmpty()){
            BinaryNode currentNode = linkedList.pollLast();

            if(currentNode.getRight() != null){
                linkedList.add(currentNode.getRight());
            }

            if(currentNode.getLeft() != null){
                linkedList.add(currentNode.getLeft());
            }

            System.out.println(currentNode.getNumber());
        }
    }

if(currentNode.getRight() != null)在IntelliJ中给我警告

  

方法调用'getRight'可能会产生NullPointerException

有人可以给我一个如何获得NullPointerException的示例。

BinaryTree类只有一个构造函数

public class BinaryTree {
    private BinaryNode root;

    public BinaryTree(BinaryNode root) {
        this.root = root;
    }

    // rest of code here including bfs/dfs algorithms
}

这也是Node类:

public class BinaryNode {
    private int number;
    private BinaryNode left;
    private BinaryNode right;

    public BinaryNode(int number) {
        this.number = number;
    }

    //boilerplate code here
}

2 个答案:

答案 0 :(得分:0)

pollLast的文档中提到:

Retrieves and removes the last element of this list, or returns null if this list is empty.

您应该首先尝试检查返回的内容是否为null。示例:

BinaryNode currentNode = linkedList.pollLast();
if(currentNode != null && currentNode.getRight() != null)

答案 1 :(得分:0)

您收到此警告,因为以下变量

BinaryNode currentNode = linkedList.pollLast();

在任何给定时间都可以为null

if(currentNode.getRight() != null){
    linkedList.add(currentNode.getRight());
}

如果currentNode的值为空,将抛出空指针异常。

可以通过如下检查currentNode的值是否为空来避免这种情况:

   while(!linkedList.isEmpty()){
        BinaryNode currentNode = linkedList.pollLast();

        if (currentNode != null) { //Null check is here
            if(currentNode.getRight() != null){
                linkedList.add(currentNode.getRight());
            }

            if(currentNode.getLeft() != null){
                linkedList.add(currentNode.getLeft());
            }

            System.out.println(currentNode.getNumber());
        }
    }