Java: null pointer exception when unboxing Integer?

后端 未结 3 690
悲&欢浪女
悲&欢浪女 2020-12-03 03:09

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

private void setSiblings(PhylogenyTree node, Color color) throws InvalidCellNumberExceptio         


        
相关标签:
3条回答
  • 2020-12-03 03:39

    Check for inverse.containsKey(animal), BiMap<PhylogenyTree, Integer>. The inverse might not have the animal.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 04:04

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

    From all the posted code, I can "guess" one of these are a potential NullPointerException (NPE).

    node may be null and calling node.getParent.

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

    One of the siblings may be null and invoking sibling.equals may throw an 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.. .

    0 讨论(0)
提交回复
热议问题