23

此代码导致空指针异常。我不知道为什么:

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);
        }
    }
}

我在调试器中检查过它,所有的局部变量都是非空的。这怎么可能发生?BiMap 来自谷歌收藏。

4

3 回答 3

68

空指针异常是对inverse.get(animal). 如果inverse不包含 key animal,则返回null, "of type" Integer。鉴于赋值是对int引用的,Java 将值拆箱到 anint中,从而导致空指针异常。

您应该检查inverse.containsKey(animal)Integer用作局部变量类型以避免拆箱并采取相应措施。适当的机制取决于您的上下文。

于 2009-11-28T05:46:16.937 回答
4

检查inverse.containsKey(animal), BiMap<PhylogenyTree, Integer>. 逆可能没有动物。

于 2009-11-28T08:31:25.787 回答
-1

你必须有一个堆栈跟踪。它准确地说明了发生这种情况的路线。发布它,我们可以知道。

从所有发布的代码中,我可以“猜测”其中一个是潜在的 NullPointerException (NPE)。

node可能为 null 并调用node.getParent.

节点的父节点可能为 null,调用parent.getChildren可能会引发 NPE。

其中一个兄弟姐妹可能为空,并且调用sibling.equals可能会引发 NPE。

cellInfo 可能为 null 并cellInfo.inverse会抛出它。

最后返回的“inverse”可能为 null 并且inverse.get()会抛出它。

呸!...

所以,为了避免这种疯狂的猜测,你为什么不发布你的堆栈跟踪,我们会发现?

它应该是这样的:

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

ETC.. 。

于 2009-11-28T05:59:22.247 回答