Domanda

This is part of a binary tree class, here is the find function, given the key to find the node in the tree, if not found return null, however this part have been recognized as dead code, when I move the if(current==null) statement to the bottom of inside while loop, it works, why? is it the same?

public class Tree {
    public Node root;

    public Node find(int key) {
        Node current = root;
        while (current.key != key) {
            if (current == null) { //dead code here, why?
                return null;
            }

            if (key < current.key) {
                current = current.leftChild;
            } else if (key > current.key) {
                current = current.rightChild;
            }
        }
        return current;
    }
}

public class Node {
    public char label;
    public boolean visited = false;
    public int key;
    public float data;

    public Node leftChild;
    public Node rightChild;

}
È stato utile?

Soluzione

If current is null it will never reach to the null check as you are accessing current.key beforehand it will throw a nullPointerException If you move the if(current==null) to bottom as you are assigning new value before it won't be a dead code. (as the current.leftChild and current.rightChild might be null)

Altri suggerimenti

Because

while (current.key != key) // <-- current.key would throw NPE if current was null.

On the statement before, you're dereferencing current.key. If current == null, you will have an NPE. If it is not null, then the if check is meaningless since it will never be reached.

What you probably intended to do was move the if check to before the loop instead:

public Node find(int key) {
    if (root == null) { 
        return null;
    }
    Node current = root;
    while (current.key != key) {
        if (key < current.key) {
            current = current.leftChild;
        } else if (key > current.key) {
            current = current.rightChild;
        }
    }
    return current;
}

This would give you the intended behavior that you want.

while (current.key != key) {
        if (current == null) { //dead code here, why?
            return null;
        }

in your while condition you are already making sure that current is not null (by using current.key!=key) , so there's no point in rechecking it in if(current==null). if current=null, then you will get a NullPointerException in your while() and you will not even reach the if condition.

If current.key has not already thrown a NullPointerException through the attempt to access the key member, current cannot possibly be null at the beginning of the while loop. When the test is moved to the bottom of the loop, current has been assigned a new value which the compiler recognizes as potentially null.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top