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

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

我在调试器中检查了它,并且所有局部变量都是非null。这怎么可能发生? BiMap来自Google Collections。

有帮助吗?

解决方案

空指针异常是取消装箱inverse.get(animal)结果的结果。如果inverse不包含密钥animal,则返回<!>,<!>类型<!>的引号; null。鉴于赋值是Integer引用,Java将值拆分为int,从而导致空指针异常。

您应该检查inverse.containsKey(animal)或使用<=>作为本地变量类型,以避免取消装箱并采取相应措施。正确的机制取决于你的背景。

其他提示

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

您必须拥有堆栈跟踪。它确切地说明发生了什么线。发布它,我们可以告诉。

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

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

节点的父节点可能为null,并且调用parent.getChildren可能会抛出NPE。

其中一个兄弟姐妹可能是null并且调用sibling.equals可能会抛出一个NPE。

cellInfo可能为null,cellInfo.inverse将抛出它。

最后<!>“;反<!>”;返回可能为null,inverse.get()将抛出它。

呼!! ...

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

应该是这样的:

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

等..

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top