vote up 0 vote down star

This code is causing a null pointer exception. I have no idea why:

private void setSiblings(PhylogenyTree node, Color color) throws InvalidCellNumberException {
    PhylogenyTree parent = node.getParent();

    for (PhylogenyTree sibling : parent.getChildren()) {
        if (! sibling.equals(node)) {
            Animal animal = sibling.getAnimal();
            BiMap<PhylogenyTree, Integer> inverse = cellInfo.inverse();
            int cell = inverse.get(animal); // null pointer exception here
            setCellColor(cell, color);
        }
    }
}

I've examined it in the debugger, and all the local variables are non-null. How else could this be happening? The BiMap is from Google Collections.

flag

72% accept rate
-1 - you didn't include a stacktrace. Are you ever going to learn??? – Stephen C Nov 28 at 9:58
1  
Well, he included the line the exception was thrown. I don't think the NullPointerException stacktrace is helpful in this case, besides for pointing the line – notnoop Nov 28 at 13:50

3 Answers

vote up 14 vote down check

The null pointer exception is a result of unboxing the result of inverse.get(animal). If inverse doesn't contain the key animal, it returns null, "of type" Integer. Given that the assignment is to an int reference, Java unboxes the value into an int, resulting in a null pointer exception.

You should either check for inverse.containsKey(animal) or use Integer as the local variable type to avoid unboxing and act accordingly. The proper mechanism depends on your context.

link|flag
+1: Nice guess .... – Oscar Reyes Nov 28 at 6:01
vote up 3 vote down

check for inverse.containsKey(animal), BiMap inverse might not have the animal.

link|flag
vote up 1 vote down

You must have a stacktrace. It says exactly what was line where that happened. Post it and we can tell.

From all the posted code I can "guess" one of these are potential NullPointerException

node may be null and calling node.getParent

The node's parent may be null and invoking parent.getChildren may throw Npe

One o the sibling may be null and invoking sibling.equals may throw Npe

cellInfo may be null and cellInfo.inverse will throw it.

Finally the "inverse" returned may be null and inverse.get() will throw it.

Phew!!...

So, to avoid doing this wild guessings why don't you just post your stacktrace and we find out?

It should something like:

 java.lang.NullPointerException: null
 at YourClass.setSiblings( YouClass.java:22 )
 at YourClass.setSiblng( YourClass.java: XX )

etc.. .

link|flag

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.