Darrel Hoffman
Darrel Hoffman

Reputation: 4646

Eclipse warning: Cannot be null?

I'm getting what I think is a spurious warning from Eclipse on the following code, used to count the number of times a given element appears in a binary tree:

public int count(E item)
{
    int count = 0;
    Node crnt = root;
    //First seek the item in the tree
    while (crnt != null)
    {
        int compare = crnt.data.compareTo(item);
        if (compare > 0)
            crnt = crnt.right;
        else if (compare < 0)
            crnt = crnt.left;
        else
        {
            //Shortcut if not allowing duplicate entries
            if (!allowDuplicates)
                return 1;
            count++;
            //Duplicates are always stored to the right
            while (crnt != null) // <--Warning appears here
            {
                crnt = crnt.right;
                if (crnt.data.compareTo(item) == 0)
                    count++;
                else
                    break;
            }
        }
    }
    return count;
}

(I could show you the Node class, but it's nothing surprising. Just an `E for the data and two Node pointers for left and right children.)

Am I missing something or is this a bug in Eclipse? Because it seems like it's perfectly possible, and in fact expected for crnt to be possibly null in this case, once it runs out of right children. Granted it won't be null the first time it hits this loop, but usually the IDE is smart enough to realize when the value of the variable changes within the loop. Not this time, however. Eclipse is suggesting I put a @SuppressWarnings("null") on this, or I could go into the settings and turn off this warning altogether, but I don't think it should be necessary, and I hate suppressing or ignoring warnings where they might be useful.

Upvotes: 0

Views: 247

Answers (1)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44448

crnt will still be different from null because it is in the else clause of the if-elseif-else statement that might change crnt. Its value will never have changed when it hits the second while statement.

It's doing exactly as it should: telling you that the value of crnt will never be null when that code hits and that the additional check in the while unnecessary is.

Per avice by David Wallace: there is no possibility that the inner loop will be null because the crnt object is already accessed prior to that by the line int compare = crnt.data.compareTo(item);, essentially forming a prerequisite that crnt must not be null.

Upvotes: 4

Related Questions